@PostMapping("/login") public Object login(@RequestBody String body) { String username = JacksonUtil.parseString(body, "username"); String password = JacksonUtil.parseString(body, "password"); if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) { return ResponseUtil.badArgument(); } Subject currentUser = SecurityUtils.getSubject(); try { currentUser.login(new UsernamePasswordToken(username, password)); } catch (UnknownAccountException uae) { return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, "用户帐号或密码不正确"); } catch (LockedAccountException lae) { return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, "用户帐号已锁定不可用"); } catch (AuthenticationException ae) { return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, ae.getMessage()); } return ResponseUtil.ok(currentUser.getSession().getId()); }
@PostMapping("/login") @ResponseBody public ResponseBo login(String username, String password, String code, Boolean rememberMe) { if (!StringUtils.isNotBlank(code)) { return ResponseBo.warn("验证码不能为空!"); } Session session = super.getSession(); String sessionCode = (String) session.getAttribute(CODE_KEY); if (!code.equalsIgnoreCase(sessionCode)) { return ResponseBo.warn("验证码错误!"); } // 密码 MD5 加密 password = MD5Utils.encrypt(username.toLowerCase(), password); UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe); try { Subject subject = getSubject(); if (subject != null) subject.logout(); super.login(token); this.userService.updateLoginTime(username); return ResponseBo.ok(); } catch (UnknownAccountException | IncorrectCredentialsException | LockedAccountException e) { return ResponseBo.error(e.getMessage()); } catch (AuthenticationException e) { return ResponseBo.error("认证失败!"); } }
@PostMapping("/adminlogin") public String adminLogin(String username, String password, String code, HttpSession session, @RequestParam(defaultValue = "0") Boolean rememberMe, RedirectAttributes redirectAttributes) { String index_code = (String) session.getAttribute("index_code"); if (index_code == null || StringUtils.isEmpty(code) || !index_code.equalsIgnoreCase(code)) { redirectAttributes.addFlashAttribute("error", "验证码不正确"); } else { try { // 添加用户认证信息 Subject subject = SecurityUtils.getSubject(); if (!subject.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe); //进行验证,这里可以捕获异常,然后返回对应信息 subject.login(token); } } catch (AuthenticationException e) { e.printStackTrace(); log.error(e.getMessage()); redirectAttributes.addFlashAttribute("error", "用户名或密码错误"); redirectAttributes.addFlashAttribute("username", username); return redirect("/adminlogin"); } } return redirect("/admin/index"); }
@Override protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) { log.error("Validate token fail, token:{}, error:{}", token.toString(), e.getMessage()); return false; }
/** * 表单的/login POST请求首先会被Shiro拦截处理,在认证失败之后才会触发调用此方法 * * @param request * @param model * @return */ @RequestMapping(value = "/admin/login", method = RequestMethod.POST) public String loginFailure(HttpServletRequest request, Model model) { //获取认证异常的类名 AuthenticationException ae = (AuthenticationException) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME); if (ae != null) { model.addAttribute("error", ae.getMessage()); return "admin/pub/login"; } else { return "redirect:/admin"; } }
@ExceptionHandler(AuthenticationException.class) @ResponseStatus(HttpStatus.UNAUTHORIZED) @ResponseBody public Response<Void> handleException(AuthenticationException e) { log.error(e.getMessage()); shiroEventListener.afterLogin(currentUserName.get(),false,e.getMessage()); ShiroExceptionHandler.remove(); return new Response<>(HttpStatus.UNAUTHORIZED.value() + "", e.getMessage(), null); } //无权限的请求,返回403,前端会进行页面跳转到登录页面
@ExceptionHandler(AuthenticationException.class) @ResponseStatus(value = HttpStatus.UNAUTHORIZED) public Object handUnauthorizedException(AuthenticationException e) { return ServerResponse.createByErrorCodeMessage(HttpStatus.UNAUTHORIZED.value(), e.getMessage()); }
@Override protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) { log.warn("onLoginFailure ['{}'] -> login failed ({}): {}", token, request.getRemoteAddr(), e.getMessage()); failedAuths.mark(); return super.onLoginFailure(token, e, request, response); }
@ResponseStatus(HttpStatus.UNAUTHORIZED) @ExceptionHandler(AuthenticationException.class) public Object handleAuthenticationException(AuthenticationException e, HttpServletRequest request) { logger.error("会话认证失败", e); if (!HttpSpy.isAjaxRequest(request)) { return asModelAndView(e); } return DataKit.buildResponse(ReplyCode.TxnSessionUnauthenticated, e.getMessage()); }
@Override public java.util.Optional<Principal> authenticate(BasicCredentials credentials) throws AuthenticationException { Subject subject = SecurityUtils.getSubject(); try { subject.login(new UsernamePasswordToken(credentials.getUsername(), credentials.getPassword(), false)); User user = new User(subject); return Optional.of(user); } catch (UnknownAccountException | IncorrectCredentialsException | LockedAccountException e) { logger.log(Level.WARNING, e.getMessage(), e); } catch (org.apache.shiro.authc.AuthenticationException ae) { logger.log(Level.WARNING, ae.getMessage(), ae); } return Optional.empty(); }
@PostMapping("/login") @ResponseBody public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe) { UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe); Subject subject = SecurityUtils.getSubject(); try { subject.login(token); return success(); } catch (AuthenticationException e) { String msg = "用户或密码错误"; if (StringUtils.isNotEmpty(e.getMessage())) { msg = e.getMessage(); } return error(msg); } }
public AuthenticationInfo authenticate( AuthenticationToken token ) throws AuthenticationException { try { return this.getSecurityManager().authenticate( token ); } catch ( org.apache.shiro.authc.AuthenticationException e ) { throw new AuthenticationException( e.getMessage(), e ); } }
public Subject login( AuthenticationToken token ) throws AuthenticationException { try { Subject subject = this.getSubject(); subject.login( token ); return subject; } catch ( org.apache.shiro.authc.AuthenticationException e ) { throw new AuthenticationException( e.getMessage(), e ); } }
@Override protected boolean onLoginFailure(final AuthenticationToken token, final AuthenticationException e, final ServletRequest request, final ServletResponse response) { if (e instanceof AuthenticationInProgressException) { // negotiate is processing final String protocol = this.getAuthzHeaderProtocol(request); NegotiateAuthenticationFilter.LOGGER.debug("Negotiation in progress for protocol: {}", protocol); this.sendChallengeDuringNegotiate(protocol, response, ((NegotiateToken) token).getOut()); return false; } NegotiateAuthenticationFilter.LOGGER.warn("login exception: {}", e.getMessage()); // do not send token.out bytes, this was a login failure. this.sendChallengeOnFailure(response); this.setFailureAttribute(request, e); return true; }
NegotiateAuthenticationFilter.LOGGER.warn("login exception: {}", e.getMessage()); // do not send token.out bytes, this was a login failure. this.sendChallengeOnFailure(response); this.setFailureAttribute(request, e); return true; } /** * Sets the failure attribute. * * @param request * the request * @param ae * the ae */ protected void setFailureAttribute(final ServletRequest request, final AuthenticationException ae) { final String className = ae.getClass().getName();
@POST @Produces("application/json") public String login(@FormParam("username") String username, @FormParam("password") String password) throws AuthenticationException{ Subject subject = SecurityUtils.getSubject(); if(!subject.isAuthenticated()) try { UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password); usernamePasswordToken.setRememberMe(false); subject.login(usernamePasswordToken); logger.info("User {} login", ShiroUtils.getUserId(subject)); Session session = subject.getSession(true); JSONStringer stringer = new JSONStringer(); stringer.object().key("portofinoSessionId").value(session.getId()).endObject(); return stringer.toString(); } catch (AuthenticationException e) { logger.warn("Login failed for '" + username + "': " + e.getMessage(), e); } return "{}"; }
@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); }
public Subject authenticate(String realmName, AuthenticationToken authenticationToken) throws AuthenticationException { org.apache.shiro.mgt.SecurityManager securityManager = securityManagers.get(realmName); org.apache.shiro.subject.Subject currentUser = new org.apache.shiro.subject.Subject.Builder(securityManager).buildSubject(); UsernamePasswordToken token = new UsernamePasswordToken( (String) authenticationToken.getPrincipal(), (char []) authenticationToken.getCredentials()); try { currentUser.login(token); Subject subject = new Subject(); return subject; } catch (org.apache.shiro.authc.AuthenticationException ae) { throw new AuthenticationException(ae.getMessage()); } } }
@Override //KNOX-534 overriding this method to be able to audit authentication exceptions protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws org.apache.shiro.authc.AuthenticationException { try { return super.doGetAuthenticationInfo(token); } catch ( org.apache.shiro.authc.AuthenticationException e ) { auditor.audit( Action.AUTHENTICATION , token.getPrincipal().toString(), ResourceType.PRINCIPAL, ActionOutcome.FAILURE, e.getMessage() ); ShiroLog.failedLoginInfo(token); ShiroLog.failedLoginStackTrace(e); ShiroLog.failedLoginAttempt(e.getCause()); throw e; } }
@Override //KNOX-534 overriding this method to be able to audit authentication exceptions protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws org.apache.shiro.authc.AuthenticationException { try { return super.doGetAuthenticationInfo(token); } catch ( org.apache.shiro.authc.AuthenticationException e ) { auditor.audit( Action.AUTHENTICATION , token.getPrincipal().toString(), ResourceType.PRINCIPAL, ActionOutcome.FAILURE, e.getMessage() ); ShiroLog.failedLoginInfo(token); ShiroLog.failedLoginStackTrace(e); ShiroLog.failedLoginAttempt(e.getCause()); throw e; } }