@Override public AuthInfo login(AuthToken token) throws RpcException { try { if (token != null) { UsernamePasswordToken upt = // new UsernamePasswordToken( // token.getUsername(), // token.getPassword().toCharArray(), // token.isRememberMe()); try { SecurityUtils.getSubject().login(upt); } catch (AuthenticationException e) { throw new RpcException(e.getMessage(), e); } } AuthInfo result = new AuthInfo(); result.setUsername((String) SecurityUtils.getSubject().getPrincipal()); result.setAuthenticated(SecurityUtils.getSubject().isAuthenticated()); boolean[] roleResult = SecurityUtils.getSubject().hasRoles(Arrays.asList(checkRoles)); for (int i = 0; i < checkRoles.length; i++) { result.getRoles().put(checkRoles[i], roleResult[i]); } return result; } catch (RpcException e) { throw e; } catch (Throwable t) { log.error(t.getMessage(), t); throw new RpcException(t.getMessage(), t); } }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String password = WebUtils.getCleanParam(request, PASSWORD); String username = WebUtils.getCleanParam(request, USERNAME); boolean rememberMe = WebUtils.isTrue(request, REMEMBER_ME); String host = request.getRemoteHost(); UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe, host); try { Subject subject = SecurityUtils.getSubject(); loginWithNewSession(token, subject); // subject.login(token); issueJson(response, HTTP_STATUS_OK, MESSAGE, "ok"); } catch (AuthenticationException e) { issue( MIME_TEXT_PLAIN, HTTP_STATUS_NOT_FOUND, "cannot authorize " + username + ": " + e.getMessage(), response); } } catch (Exception e) { issue( MIME_TEXT_PLAIN, HTTP_STATUS_INTERNAL_SERVER_ERROR, "Internal error: " + e.getMessage(), response); } }
/* 无需做链接,这是OpenID的回调地址 */ @RequiresGuest @At("/login/?/callback") public View returnPoint(String providerId, HttpServletRequest request, HttpSession session) throws Exception { SocialAuthManager manager = (SocialAuthManager) session.getAttribute("openid.manager"); if (manager == null) throw new SocialAuthException("Not manager found!"); session.removeAttribute("openid.manager"); // 防止重复登录的可能性 Map<String, String> paramsMap = SocialAuthUtil.getRequestParametersMap(request); AuthProvider provider = manager.connect(paramsMap); Profile p = provider.getUserProfile(); Subject currentUser = SecurityUtils.getSubject(); ThreadContext.bind(currentUser); OAuthToken token = new OAuthToken(p, request.getRemoteAddr()); try { currentUser.login(token); } catch (UnknownAccountException uae) { return new ViewWrapper(new ForwardView("/admin/index"), "帐号不存在"); } catch (IncorrectCredentialsException ice) { return new ViewWrapper(new ForwardView("/admin/index"), "证书验证失败"); } catch (LockedAccountException lae) { return new ViewWrapper(new ForwardView("/admin/index"), "帐号已被锁定"); } catch (ExcessiveAttemptsException eae) { return new ViewWrapper(new ForwardView("/admin/index"), "尝试的次数太多"); } catch (AuthenticationException ae) { return new ViewWrapper(new ForwardView("/admin/index"), ae.getMessage()); } return new ViewWrapper(new ServerRedirectView("/admin/main.rk"), null); }
@Override public int authenticateByEmailAddress( long companyId, String emailAddress, String password, Map<String, String[]> headerMap, Map<String, String[]> parameterMap) throws AuthException { _log.info("authenticateByEmailAddress"); UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(emailAddress, password); Subject currentUser = SecurityUtils.getSubject(); try { currentUser.login(usernamePasswordToken); boolean authenticated = currentUser.isAuthenticated(); if (authenticated) { _log.info("authenticated"); return SKIP_LIFERAY_CHECK; } else { return FAILURE; } } catch (AuthenticationException e) { _log.error(e.getMessage(), e); throw new AuthException(e.getMessage(), e); } }
/** * shiro安全框架用户登录 * * @param loginUser */ private boolean authenticationByShiro(String userName, String password, boolean remeberMe) { UsernamePasswordToken token = new UsernamePasswordToken(userName, password, remeberMe); try { SecurityUtils.getSubject().login(token); } catch (AuthenticationException e) { this.addActionError(e.getMessage()); log.warn("shiro login error" + e.getMessage(), e); return false; } return true; }
/** 重写父类方法,当登录失败将异常信息设置到request的attribute中 */ @Override protected void setFailureAttribute(ServletRequest request, AuthenticationException ae) { if (ae instanceof IncorrectCredentialsException) { request.setAttribute(getFailureKeyAttribute(), "用户名密码不正确"); } else { request.setAttribute(getFailureKeyAttribute(), ae.getMessage()); } }
@Override public void changePassword(String userId, String oldPassword, String newPassword) throws UserNotFoundException, InvalidCredentialsException { // first authenticate the user try { UsernamePasswordToken authenticationToken = new UsernamePasswordToken(userId, oldPassword); if (realmSecurityManager.authenticate(authenticationToken) == null) { throw new InvalidCredentialsException(); } } catch (AuthenticationException e) { log.debug("User failed to change password reason: " + e.getMessage(), e); throw new InvalidCredentialsException(); } // if that was good just change the password changePassword(userId, newPassword); }
@Test public void testHelloWorld() { // 1 获取SecurityManager工厂 Factory<org.apache.shiro.mgt.SecurityManager> securityManagerFactory = new IniSecurityManagerFactory("classpath:shiro.ini"); // 2 得到SecurityManager实例 SecurityManager securityManager = securityManagerFactory.getInstance(); SecurityUtils.setSecurityManager(securityManager); // 3 得到subject及创建用户名/密码 Token Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123"); // 4 验证 try { subject.login(token); } catch (AuthenticationException e) { e.printStackTrace(); } Assert.assertEquals(true, subject.isAuthenticated()); // 5 退出 subject.logout(); }
/* * 覆盖默认实现,打印日志便于调试,查看具体登录是什么错误。 *(可以扩展把错误写入数据库之类的。) * (non-Javadoc) * @see org.apache.shiro.web.filter.authc.FormAuthenticationFilter#onLoginFailure(org.apache.shiro.authc.AuthenticationToken, org.apache.shiro.authc.AuthenticationException, javax.servlet.ServletRequest, javax.servlet.ServletResponse) */ @Override protected boolean onLoginFailure( AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) { if (log.isDebugEnabled()) { Class<?> clazz = e.getClass(); if (clazz.equals(AuthenticationException.class)) { log.debug(Exceptions.getStackTraceAsString(e)); } } return super.onLoginFailure(token, e, request, response); }
protected void setFailureAttribute(ServletRequest request, AuthenticationException ae) { String className = ae.getClass().getName(); request.setAttribute(getFailureKeyAttribute(), className); }