Search in sources :

Example 51 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project wechat by dllwh.

the class ShiroHelper method login.

/**
 * ----------------------------------------------------- Fields end
 */
public static AjaxJson login(String userName, String passWord) {
    // 用户名密码令牌
    UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord);
    token.setRememberMe(false);
    String logMsg = "", resultMsg = "";
    AjaxJson ajaxJson = new AjaxJson();
    boolean suc = false;
    // 获得当前登录用户对象Subject,现在状态为 “未认证”
    Subject subject = SecurityUtils.getSubject();
    try {
        subject.login(token);
    } catch (UnknownAccountException uae) {
        logMsg = "对用户[" + userName + "]进行登录验证..验证未通过,未知账户";
        resultMsg = MessageConstant.LOGIN_USER_UNKNOWN;
    } catch (IncorrectCredentialsException ice) {
        logMsg = "对用户[" + userName + "]进行登录验证..验证未通过,错误的凭证";
        resultMsg = MessageConstant.LOGIN_USER_REEOE;
    } catch (LockedAccountException lae) {
        logMsg = "对用户[" + userName + "]进行登录验证..验证未通过,账户已锁定";
        resultMsg = MessageConstant.LOGIN_USER_LOCK;
    } catch (DisabledAccountException dae) {
        logMsg = "对用户[" + userName + "]进行登录验证..验证未通过,帐号已被禁用";
        resultMsg = MessageConstant.LOGIN_USER_DISABLED;
    } catch (ExpiredCredentialsException ece) {
        logMsg = "对用户[" + userName + "]进行登录验证..验证未通过,帐号已过期";
        resultMsg = MessageConstant.LOGIN_USER_EXPIRED;
    } catch (ExcessiveAttemptsException eae) {
        logMsg = "对用户[" + userName + "]进行登录验证..验证未通过,用户名或密码错误次数过多";
        resultMsg = MessageConstant.LOGIN_USER_MORE;
    } catch (UnauthorizedException e) {
        logMsg = "对用户[" + userName + "]进行登录验证..验证未通过,您没有得到相应的授权!";
        resultMsg = MessageConstant.LOGIN_USER_UNAUTHORIZED;
    } catch (AuthenticationException ae) {
        logMsg = "对用户[" + userName + "]进行登录验证..验证未通过," + ae.getMessage();
        resultMsg = MessageConstant.LOGIN_ERROR;
    }
    if (subject.isAuthenticated()) {
        logMsg = "对用户[" + userName + "]进行登录验证..验证通过";
        suc = true;
    } else {
        token.clear();
    }
    ajaxJson.setSuccess(suc);
    ajaxJson.setMsg(resultMsg);
    ajaxJson.setObj(logMsg);
    return ajaxJson;
}
Also used : DisabledAccountException(org.apache.shiro.authc.DisabledAccountException) IncorrectCredentialsException(org.apache.shiro.authc.IncorrectCredentialsException) AuthenticationException(org.apache.shiro.authc.AuthenticationException) UnknownAccountException(org.apache.shiro.authc.UnknownAccountException) ExcessiveAttemptsException(org.apache.shiro.authc.ExcessiveAttemptsException) AjaxJson(com.cdeledu.common.base.AjaxJson) Subject(org.apache.shiro.subject.Subject) ExpiredCredentialsException(org.apache.shiro.authc.ExpiredCredentialsException) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) UnauthorizedException(org.apache.shiro.authz.UnauthorizedException) LockedAccountException(org.apache.shiro.authc.LockedAccountException)

Example 52 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project wechat by dllwh.

the class ShiroRealm method doGetAuthenticationInfo.

/**
 * @方法描述: 验证当前登录的Subject
 * @说明: 该方法的调用时机为LoginController.login()方法中执行Subject.login()时
 * @param token
 * @return
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authtoken) throws AuthenticationException {
    UsernamePasswordToken token = (UsernamePasswordToken) authtoken;
    // ① 获取当前登录的用户名
    String currentUsername = token.getUsername();
    String passWord = String.valueOf(token.getPassword());
    SysUser sysUser = new SysUser();
    SysUser currentUser = null;
    SimpleAuthenticationInfo authcInfo = null;
    try {
        sysUser.setUserName(currentUsername);
        int userCount = userService.getCountForJdbcParam(sysUser);
        if (userCount <= 0) {
            throw new UnknownAccountException();
        }
        currentUser = userService.checkUserExits(currentUsername, passWord);
    } catch (Exception e) {
        throw new UnknownAccountException();
    }
    if (currentUser != null) {
        // 账号未通过审核
        if (currentUser.getIfEnabled() != 1) {
            throw new DisabledAccountException();
        }
        // 账号未通过审核
        if (currentUser.getIfVisible() != 1) {
            throw new DisabledAccountException("账号未通过审核");
        }
        // 账号不允许登录
        if (currentUser.getLoginFlag() != 1) {
            throw new AuthenticationException("账号不允许登录");
        }
        // 账号被锁定
        if (currentUser.getIfLocked() != 1) {
            throw new ExcessiveAttemptsException("账号被锁定");
        }
        WebUtilHelper.setCurrentLoginUser(currentUser);
        authcInfo = new SimpleAuthenticationInfo(currentUser, currentUser.getPassword(), getName());
    } else {
        throw new LockedAccountException("用户名或密码错误");
    }
    return authcInfo;
}
Also used : DisabledAccountException(org.apache.shiro.authc.DisabledAccountException) SysUser(com.cdeledu.model.rbac.SysUser) SimpleAuthenticationInfo(org.apache.shiro.authc.SimpleAuthenticationInfo) AuthenticationException(org.apache.shiro.authc.AuthenticationException) UnknownAccountException(org.apache.shiro.authc.UnknownAccountException) ExcessiveAttemptsException(org.apache.shiro.authc.ExcessiveAttemptsException) AuthenticationException(org.apache.shiro.authc.AuthenticationException) DisabledAccountException(org.apache.shiro.authc.DisabledAccountException) ExcessiveAttemptsException(org.apache.shiro.authc.ExcessiveAttemptsException) LockedAccountException(org.apache.shiro.authc.LockedAccountException) UnknownAccountException(org.apache.shiro.authc.UnknownAccountException) LockedAccountException(org.apache.shiro.authc.LockedAccountException) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken)

Example 53 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project mica2 by obiba.

the class SessionsResource method createSession.

@POST
@Path("/sessions")
public Response createSession(@SuppressWarnings("TypeMayBeWeakened") @Context HttpServletRequest servletRequest, @FormParam("username") String username, @FormParam("password") String password) {
    try {
        ObibaRealm.Subject profile = userProfileService.getProfile(username);
        String realUsername = profile == null ? username : profile.getUsername();
        authenticationExecutor.login(new UsernamePasswordToken(realUsername, password));
        Subject subject = SecurityUtils.getSubject();
        String sessionId = subject.getSession().getId().toString();
        log.info("Successful session creation for user '{}' session ID is '{}'.", realUsername, sessionId);
        String locale = getPreferredLocale(subject);
        Response.ResponseBuilder builder = Response.created(UriBuilder.fromPath(JerseyConfiguration.WS_ROOT).path(SessionResource.class).build(sessionId));
        if (!Strings.isNullOrEmpty(locale))
            builder.cookie(new NewCookie("NG_TRANSLATE_LANG_KEY", locale, micaConfigService.getContextPath() + "/", null, DEFAULT_VERSION, null, DEFAULT_MAX_AGE, null, false, false));
        return builder.build();
    } catch (UserBannedException e) {
        throw e;
    } catch (AuthenticationException e) {
        log.info("Authentication failure of user '{}' at ip: '{}': {}", username, servletRequest.getRemoteAddr(), e.getMessage());
        // When a request contains credentials and they are invalid, the 403 (Forbidden) should be returned.
        return Response.status(Response.Status.FORBIDDEN).cookie().build();
    }
}
Also used : Response(javax.ws.rs.core.Response) AuthenticationException(org.apache.shiro.authc.AuthenticationException) ObibaRealm(org.obiba.shiro.realm.ObibaRealm) UserBannedException(org.obiba.shiro.web.filter.UserBannedException) Subject(org.apache.shiro.subject.Subject) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) NewCookie(javax.ws.rs.core.NewCookie) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 54 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project mica2 by obiba.

the class MicaConfigDtosTest method setup.

@Before
public void setup() {
    Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject();
    UsernamePasswordToken token = new UsernamePasswordToken("root", "secret");
    subjectUnderTest.login(token);
    setSubject(subjectUnderTest);
}
Also used : Subject(org.apache.shiro.subject.Subject) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) Before(org.junit.Before)

Example 55 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project production_ssm by megagao.

the class LoginController method ajaxLogin.

/**
 * shiro ajax登录
 */
@RequestMapping(value = "/ajaxLogin")
@ResponseBody
public Map<String, Object> ajaxLogin(@RequestParam String username, @RequestParam String password, @RequestParam(required = false) String randomcode, HttpSession session) throws Exception {
    Map<String, Object> map = CollectionsFactory.newHashMap();
    if (randomcode != null && !randomcode.equals("")) {
        // 取出session的验证码(正确的验证码)
        String validateCode = (String) session.getAttribute(VALIDATE_CODE);
        // 页面中输入的验证和session中的验证进行对比
        if (validateCode != null && !randomcode.equals(validateCode)) {
            // 如果校验失败,将验证码错误失败信息放入map中
            map.put("msg", "randomcode_error");
            // 直接返回,不再校验账号和密码
            return map;
        }
    }
    Subject currentUser = SecurityUtils.getSubject();
    if (!currentUser.isAuthenticated()) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            currentUser.login(token);
        } catch (UnknownAccountException ex) {
            map.put("msg", "account_error");
        } catch (IncorrectCredentialsException ex) {
            map.put("msg", "password_error");
        } catch (AuthenticationException ex) {
            map.put("msg", "authentication_error");
        }
    }
    // 返回json数据
    return map;
}
Also used : IncorrectCredentialsException(org.apache.shiro.authc.IncorrectCredentialsException) AuthenticationException(org.apache.shiro.authc.AuthenticationException) UnknownAccountException(org.apache.shiro.authc.UnknownAccountException) Subject(org.apache.shiro.subject.Subject) 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