Search in sources :

Example 76 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project xmall by Exrick.

the class UserController method login.

@RequestMapping(value = "/user/login", method = RequestMethod.POST)
@ApiOperation(value = "用户登录")
@SystemControllerLog(description = "登录系统")
public Result<Object> login(String username, String password, String challenge, String validate, String seccode, HttpServletRequest request) {
    // 极验验证
    GeetestLib gtSdk = new GeetestLib(GeetestLib.id, GeetestLib.key, GeetestLib.newfailback);
    // 从session中获取gt-server状态
    int gt_server_status_code = (Integer) request.getSession().getAttribute(gtSdk.gtServerStatusSessionKey);
    // 自定义参数,可选择添加
    HashMap<String, String> param = new HashMap<String, String>();
    int gtResult = 0;
    if (gt_server_status_code == 1) {
        // gt-server正常,向gt-server进行二次验证
        gtResult = gtSdk.enhencedValidateRequest(challenge, validate, seccode, param);
        System.out.println(gtResult);
    } else {
        // gt-server非正常情况下,进行failback模式验证
        System.out.println("failback:use your own server captcha validate");
        gtResult = gtSdk.failbackValidateRequest(challenge, validate, seccode);
        System.out.println(gtResult);
    }
    if (gtResult == 1) {
        // 验证成功
        Subject subject = SecurityUtils.getSubject();
        // MD5加密
        String md5Pass = DigestUtils.md5DigestAsHex(password.getBytes());
        UsernamePasswordToken token = new UsernamePasswordToken(username, md5Pass);
        try {
            subject.login(token);
            return new ResultUtil<Object>().setData(null);
        } catch (Exception e) {
            return new ResultUtil<Object>().setErrorMsg("用户名或密码错误");
        }
    } else {
        // 验证失败
        return new ResultUtil<Object>().setErrorMsg("验证失败");
    }
}
Also used : ResultUtil(cn.exrick.common.utils.ResultUtil) HashMap(java.util.HashMap) GeetestLib(cn.exrick.common.utils.GeetestLib) Subject(org.apache.shiro.subject.Subject) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) ApiOperation(io.swagger.annotations.ApiOperation) SystemControllerLog(cn.exrick.common.annotation.SystemControllerLog)

Example 77 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project dubidubi by lzzzz4.

the class LoginController method doLogin.

/**
 * @Description: 直接访问与cookie请求的url
 * @param userLoginDTO
 * @param model
 * @param request
 * @param response
 * @return
 * @throws IOException
 * @throws ClassNotFoundException
 */
@RequestMapping("/doLogin")
public String doLogin(UserLoginDTO userLoginDTO, Model model, HttpServletRequest request, HttpServletResponse response) throws IOException, ClassNotFoundException, AuthorizationException {
    boolean isSavedCookie = false;
    if (userLoginDTO == null || StringUtils.isBlank(userLoginDTO.getAccount()) || StringUtils.isBlank(userLoginDTO.getPassword())) {
        userLoginDTO = loginCookieService.getUserFromCookies(request.getCookies());
        if (userLoginDTO == null) {
            return defeatPath;
        }
        isSavedCookie = true;
    }
    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(userLoginDTO.getAccount(), userLoginDTO.getPassword());
    try {
        subject.login(token);
    } catch (LockedAccountException e) {
        e.printStackTrace();
        model.addAttribute("locked", "Y");
        return defeatPath;
    } catch (AuthenticationException e) {
        e.printStackTrace();
        model.addAttribute("wrong", "Y");
        return defeatPath;
    }
    UserDO userDO = (UserDO) subject.getPrincipal();
    request.getSession().setAttribute("user", userDO);
    // 将登录信息写入cookie
    if (!isSavedCookie) {
        loginCookieService.addLoginCookie(userLoginDTO, response);
    }
    SavedRequest savedRequest = WebUtils.getSavedRequest(request);
    if (savedRequest == null) {
        return defaultPath;
    }
    String URL = savedRequest.getRequestUrl();
    if (URL != null) {
        int URLStart = URL.indexOf("/", 1);
        String realURL = URL.substring(URLStart, URL.length());
        return "redirect:" + realURL;
    } else {
        return defaultPath;
    }
}
Also used : AuthenticationException(org.apache.shiro.authc.AuthenticationException) UserDO(cn.dubidubi.model.base.UserDO) Subject(org.apache.shiro.subject.Subject) LockedAccountException(org.apache.shiro.authc.LockedAccountException) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) SavedRequest(org.apache.shiro.web.util.SavedRequest) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 78 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project dubidubi by lzzzz4.

the class LoginController method ajaxLogin.

/**
 * @Description: ajax方式访问url
 * 404 认证错误
 * 403 账户被锁定错误
 * 500 无上传对象错误
 * 200 成功
 * @return ajax返回值对象
 * @throws IOException
 */
@RequestMapping(value = "/doLogin", headers = "X-Requested-With=XMLHttpRequest")
@ResponseBody
public AjaxResultDTO ajaxLogin(UserLoginDTO userLoginDTO, HttpServletRequest request, HttpServletResponse response) throws AuthorizationException, IOException {
    AjaxResultDTO ajaxResultDTO = new AjaxResultDTO();
    Subject subject = SecurityUtils.getSubject();
    if (StringUtils.isNotBlank(userLoginDTO.getAccount()) && StringUtils.isNotBlank(userLoginDTO.getPassword())) {
        UsernamePasswordToken token = new UsernamePasswordToken(userLoginDTO.getAccount(), userLoginDTO.getPassword());
        // 调取realm
        try {
            subject.login(token);
        } catch (LockedAccountException e) {
            // 账户被锁定
            ajaxResultDTO.setCode(403);
            e.printStackTrace();
            return ajaxResultDTO;
        } catch (AuthenticationException e) {
            // 认证错误
            ajaxResultDTO.setCode(404);
            e.printStackTrace();
            return ajaxResultDTO;
        }
    } else {
        // 无上传数值错误
        ajaxResultDTO.setCode(500);
    }
    // 往session中放入用户数据
    UserDO userDO = (UserDO) subject.getPrincipal();
    request.getSession().setAttribute("user", userDO);
    // 设置状态为成功
    ajaxResultDTO.setCode(200);
    // 设置cookie
    loginCookieService.addLoginCookie(userLoginDTO, response);
    // 得到跳转前的url
    SavedRequest savedRequest = WebUtils.getSavedRequest(request);
    // 当savedrequest对象为空
    if (savedRequest == null) {
        ajaxResultDTO.setUrl(defaultPath);
    }
    String URL = savedRequest.getRequestUrl();
    // 判断url是否为空
    if (URL != null) {
        int URLStart = URL.indexOf("/", 1);
        String realURL = URL.substring(URLStart, URL.length());
        ajaxResultDTO.setUrl(realURL);
    } else {
        ajaxResultDTO.setUrl(defaultPath);
    }
    return ajaxResultDTO;
}
Also used : AuthenticationException(org.apache.shiro.authc.AuthenticationException) UserDO(cn.dubidubi.model.base.UserDO) AjaxResultDTO(cn.dubidubi.model.base.dto.AjaxResultDTO) Subject(org.apache.shiro.subject.Subject) LockedAccountException(org.apache.shiro.authc.LockedAccountException) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) SavedRequest(org.apache.shiro.web.util.SavedRequest) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 79 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project airavata by apache.

the class LDAPUserStore method authenticate.

public boolean authenticate(String userName, Object credentials) throws UserStoreException {
    AuthenticationToken authenticationToken = new UsernamePasswordToken(userName, passwordDigester.getPasswordHashValue((String) credentials));
    AuthenticationInfo authenticationInfo;
    try {
        authenticationInfo = ldapRealm.getAuthenticationInfo(authenticationToken);
    } catch (AuthenticationException e) {
        log.warn(e.getLocalizedMessage(), e);
        return false;
    }
    return authenticationInfo != null;
}
Also used : AuthenticationToken(org.apache.shiro.authc.AuthenticationToken) AuthenticationException(org.apache.shiro.authc.AuthenticationException) AuthenticationInfo(org.apache.shiro.authc.AuthenticationInfo) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken)

Example 80 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project Workload by amoxu.

the class UserController method update.

@RequestMapping(value = "/zone/update", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8", method = { RequestMethod.POST })
@ResponseBody
public // 重置密码
String update(HttpServletRequest request) throws Exception {
    Subject currentUser = SecurityUtils.getSubject();
    String name = request.getParameter("name");
    String mail = request.getParameter("mail");
    String question = request.getParameter("question");
    String answer = request.getParameter("answer");
    AjaxResult result = new AjaxResult();
    String username = currentUser.getPrincipal().toString();
    User user = userService.findByName(username);
    if (null == user) {
        result.failed();
        result.setMsg("请重新登录后重试。");
        return JSON.toJSONString(result);
    }
    user.setQuestion(question);
    user.setAnswer(answer);
    user.setMail(mail);
    user.setUser(name);
    try {
        userService.updateUser(user);
        currentUser.logout();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUser(), user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        // 如果获取不到用户名就是登录失败,但登录失败的话,会直接抛出异常
        subject.login(token);
        result.ok();
        result.setMsg("修改成功。");
        return JSON.toJSONString(result);
    } catch (Exception e) {
        e.printStackTrace();
        throw new CustomException("请重新登录后重试。");
    }
}
Also used : AjaxResult(com.hfut.entity.AjaxResult) User(com.hfut.entity.User) CustomException(com.hfut.exception.CustomException) Subject(org.apache.shiro.subject.Subject) CustomException(com.hfut.exception.CustomException) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Aggregations

UsernamePasswordToken (org.apache.shiro.authc.UsernamePasswordToken)118 Subject (org.apache.shiro.subject.Subject)52 Test (org.junit.Test)30 AuthenticationException (org.apache.shiro.authc.AuthenticationException)28 AuthenticationToken (org.apache.shiro.authc.AuthenticationToken)28 SimpleAuthenticationInfo (org.apache.shiro.authc.SimpleAuthenticationInfo)19 AuthenticationInfo (org.apache.shiro.authc.AuthenticationInfo)16 HttpServletRequest (javax.servlet.http.HttpServletRequest)11 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)11 Test (org.testng.annotations.Test)11 LockedAccountException (org.apache.shiro.authc.LockedAccountException)10 IncorrectCredentialsException (org.apache.shiro.authc.IncorrectCredentialsException)9 UnknownAccountException (org.apache.shiro.authc.UnknownAccountException)9 HttpServletResponse (javax.servlet.http.HttpServletResponse)8 DelegatingSubject (org.apache.shiro.subject.support.DelegatingSubject)7 Session (org.apache.shiro.session.Session)6 SimplePrincipalCollection (org.apache.shiro.subject.SimplePrincipalCollection)6 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)6 DisabledAccountException (org.apache.shiro.authc.DisabledAccountException)4 AuthorizationInfo (org.apache.shiro.authz.AuthorizationInfo)4