org.hibernate.validator.constraints.NotEmpty#org.apache.shiro.authc.AuthenticationException源码实例Demo

下面列出了org.hibernate.validator.constraints.NotEmpty#org.apache.shiro.authc.AuthenticationException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

/**
 * Authenticates a user and retrieves its information.
 *
 * @param token
 *            the authentication token
 * @throws AuthenticationException
 *             if there is an error during authentication.
 */
@Override
protected IamAuthenticationInfo doAuthenticationInfo(Oauth2SnsAuthenticationToken token) throws AuthenticationException {
	ProviderSupport.checkSupport(token.getSocial().getProvider());

	/**
	 * Obtain the account information bound by openId.
	 * {@link Oauth2AuthorizingBoundMatcher#doCredentialsMatch()}
	 */
	Parameter parameter = new SnsAuthorizingParameter(token.getSocial().getProvider(), token.getSocial().getOpenId(),
			token.getSocial().getUnionId());
	IamPrincipalInfo info = configurer.getIamAccount(parameter);
	log.info("Got authentication accountInfo: {}, by sns parameter: {}", toJSONString(info), toJSONString(parameter));

	if (nonNull(info) && !isBlank(info.getPrincipal())) {
		// Authenticate attributes.(roles/permissions/rememberMe)
		PrincipalCollection principals = createPermitPrincipalCollection(info);
		return new Oauth2SnsAuthenticationInfo(info, principals, getName());
	}
	return EmptyOauth2AuthenicationInfo.EMPTY;
}
 
源代码2 项目: cjs_ssms   文件: UUserRealm.java
/**
 * 登录认证,在权限认证前执行
 *
 * @param token
 * @return AuthenticationInfo
 * @throws AuthenticationException
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  String username = token.getPrincipal().toString();
  UUser user = userMService.findUserByUserName(username);
  if (null == user) {
    return null;
  } else {
    /**
     * info中principal选择方案:1.username, 2.User, 3.UserWithRoleAndPermission
     * 各有优劣,这里选择使用username
     *
     * EAO isssue: 新建对象WholeUser,有属性roles,permissions,登录时产生此对象作为principals,则authorization时无需再和sql交互
     * 1.优势: 减少sql交互,
     * 2.劣势:缓存大,对变更的用户信息反馈不及时
     * 适用: 变化不大信息量少,但权限校验频繁的用户类型.
     *
     * SimpleAuthorizationInfo: param: principal检查源码最后被强转为Collection不知何意??
     */
    SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), "UserRealm");
    return info;
  }
}
 
源代码3 项目: supplierShop   文件: SysLoginController.java
@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);
    }
}
 
源代码4 项目: spring-boot-demo   文件: AuthRealm.java
/**
 * 认证(主要是用来进行身份认证的,也就是说验证用户输入的账号和密码是否正确)
 *
 * @param token
 * @return
 * @throws AuthenticationException
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    log.info("调用认证方法");
    //获取用户的输入的账号.
    String username = (String) token.getPrincipal();
    if (username == null) {
        throw new AuthenticationException("账号名为空,登录失败!");
    }

    log.info("credentials:" + token.getCredentials());
    UserInfo userInfo = userInfoService.findByUsername(username);
    if (userInfo == null) {
        throw new AuthenticationException("不存在的账号,登录失败!");
    }

    SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
            userInfo,                                               //用户
            userInfo.getPassword(),                                 //密码
            ByteSource.Util.bytes(userInfo.getCredentialsSalt()),   //加盐后的密码
            getName()                                               //指定当前 Realm 的类名
    );
    return authenticationInfo;
}
 
源代码5 项目: SpringAll   文件: ShiroRealm.java
/**
 * 登录认证
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	String userName = (String) token.getPrincipal();
	String password = new String((char[]) token.getCredentials());

	System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
	User user = userMapper.findByUserName(userName);

	if (user == null) {
		throw new UnknownAccountException("用户名或密码错误!");
	}
	if (!password.equals(user.getPassword())) {
		throw new IncorrectCredentialsException("用户名或密码错误!");
	}
	if (user.getStatus().equals("0")) {
		throw new LockedAccountException("账号已被锁定,请联系管理员!");
	}
	SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
	return info;
}
 
源代码6 项目: Moss   文件: LdapRealm.java
@Override
protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken authenticationToken,
                                                        LdapContextFactory ldapContextFactory) throws NamingException {
    String token = (String) authenticationToken.getCredentials();
    // 解密获得username,用于和数据库进行对比
    String username = JwtUtil.getUsername(token);

    if (null==username  || !JwtUtil.verify(token, username)) {
        throw new AuthenticationException("token认证失败!");
    }
    LdapContext ctx = null;
    try {
        ctx = ldapContextFactory.getLdapContext(username, null);
    } catch (Throwable e) {
        LOGGER.error(e.getMessage(), e);
        return null;
    } finally {
        LdapUtils.closeContext(ctx);
    }
    return new SimpleAuthenticationInfo(token, token, "MyRealm");
}
 
源代码7 项目: web-flash   文件: ApiRealm.java
/**
 * 默认使用此方法进行用户名正确与否验证,错误抛出异常即可。
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
    String token = (String) auth.getCredentials();
    // 解密获得username,用于和数据库进行对比
    String username = JwtUtil.getUsername(token);
    if (username == null) {
        throw new AuthenticationException("token invalid");
    }

    ShiroUser userBean =  ShiroFactroy.me().shiroUser(userService.findByAccount(username));
    if (userBean == null) {
        throw new AuthenticationException("User didn't existed!");
    }
    try {
        if (!JwtUtil.verify(token, username, userBean.getPassword())) {
            throw new AuthenticationException("Username or password error");
        }
    }catch (Exception e){
        throw  new AuthenticationException(e.getMessage());
    }

    return new SimpleAuthenticationInfo(token, token, "my_realm");
}
 
源代码8 项目: EasyReport   文件: MyShiroRealm.java
@Override
protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token)
    throws AuthenticationException {
    final String account = (String)token.getPrincipal();
    final User user = this.membershipFacade.getUser(account);

    if (user == null) {
        throw new UnknownAccountException();
    }
    if (user.getStatus() == 0) {
        throw new LockedAccountException();
    }

    // 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配
    return new SimpleAuthenticationInfo(
        user.getAccount(), user.getPassword(),
        ByteSource.Util.bytes(user.getCredentialsSalt()),
        getName());
}
 
源代码9 项目: SpringAll   文件: ShiroRealm.java
/**
 * 登录认证
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	String userName = (String) token.getPrincipal();
	String password = new String((char[]) token.getCredentials());

	System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
	User user = userMapper.findByUserName(userName);

	if (user == null) {
		throw new UnknownAccountException("用户名或密码错误!");
	}
	if (!password.equals(user.getPassword())) {
		throw new IncorrectCredentialsException("用户名或密码错误!");
	}
	if (user.getStatus().equals("0")) {
		throw new LockedAccountException("账号已被锁定,请联系管理员!");
	}
	SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
	return info;
}
 
源代码10 项目: onedev   文件: OpenIdConnector.java
protected RuntimeException buildException(ErrorObject error) {
	String errorMessage;
	if ("redirect_uri_mismatch".equals(error.getCode())) {
		errorMessage = "Redirect uri mismatch: make sure the server url specified in system setting is the same as "
				+ "root part of the authorization callback url specified at " + getName() + " side";
	} else {
		List<String> details = new ArrayList<>();
		if (error.getCode() != null) 
			details.add("code: " + error.getCode());
		if (error.getDescription() != null)
			details.add("description: " + error.getDescription());
		if (error.getHTTPStatusCode() != 0)
			details.add("http status code: " + error.getHTTPStatusCode());
		
		errorMessage = "OIDC response error (" + StringUtils.join(details, ", ") + ")";
	}
	
	return new AuthenticationException(errorMessage);
}
 
源代码11 项目: MyBlog   文件: MyRealm.java
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    if (token == null || StringUtils.isBlank((String) token.getPrincipal())) {
        return null;
    }
    //根据token中的用户名查库,获得user对象
    UserPo userPo = userService.queryUserByName((String) token.getPrincipal());
    if (userPo == null) {
        return null;
    }
    //SimpleAuthenticationInfo代表该用户的认证信息,其实就是数据库中的用户名、密码、加密密码使用的盐
    //存在数据库中的密码是对用户真是密码通过md5加盐加密得到的,保证安全,及时数据泄露,也得不到真正的用户密码
    //getName()返回该realm的名字,代表该认证信息的来源是该realm,作用不大,一般都是单realm
    //该方法返回后,上层会对token和SimpleAuthenticationInfo进行比较,首先比较Principal(),然后将token的Credentials
    //进行md5加上SimpleAuthenticationInfo中的盐加密,加密结果和SimpleAuthenticationInfo的Credentials比较
    return new SimpleAuthenticationInfo(
            userPo.getUserName(), userPo.getPassword(), ByteSource.Util.bytes(userPo.getUserName()), getName());
}
 
源代码12 项目: cassandra-reaper   文件: LoginResource.java
@Path("/login")
@POST
public void login(
    @FormParam("username") String username,
    @FormParam("password") String password,
    @FormParam("rememberMe") boolean rememberMe,
    @Auth Subject subject) throws IOException {

  ensurePresent(username, "Invalid credentials: missing username.");
  ensurePresent(password, "Invalid credentials: missing password.");

  try {
    subject.login(new UsernamePasswordToken(username, password, rememberMe));
  } catch (AuthenticationException e) {
    throw new IncorrectCredentialsException("Invalid credentials combination for user: " + username);
  }
}
 
源代码13 项目: LuckyFrameWeb   文件: LoginController.java
@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);
    }
}
 
源代码14 项目: ruoyiplus   文件: SysLoginController.java
@PostMapping("/login")
@ResponseBody
public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe)
{
    if(rememberMe == null) rememberMe =false;
    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);
    }
}
 
源代码15 项目: SpringAll   文件: ShiroRealm.java
/**
 * 用户认证
 *
 * @param authenticationToken 身份认证 token
 * @return AuthenticationInfo 身份认证信息
 * @throws AuthenticationException 认证相关异常
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    // 这里的 token是从 JWTFilter 的 executeLogin 方法传递过来的,已经经过了解密
    String token = (String) authenticationToken.getCredentials();

    String username = JWTUtil.getUsername(token);

    if (StringUtils.isBlank(username))
        throw new AuthenticationException("token校验不通过");

    // 通过用户名查询用户信息
    User user = SystemUtils.getUser(username);

    if (user == null)
        throw new AuthenticationException("用户名或密码错误");
    if (!JWTUtil.verify(token, username, user.getPassword()))
        throw new AuthenticationException("token校验不通过");
    return new SimpleAuthenticationInfo(token, token, "shiro_realm");
}
 
源代码16 项目: jeecg-boot-with-activiti   文件: TokenUtils.java
/**
 * 验证Token
 */
public static boolean verifyToken(HttpServletRequest request, ISysBaseAPI sysBaseAPI, RedisUtil redisUtil) {
    String token = request.getParameter("token");

    // 解密获得username,用于和数据库进行对比
    String username = JwtUtil.getUsername(token);
    if (username == null) {
        throw new AuthenticationException("token非法无效!");
    }

    // 查询用户信息
    LoginUser user = sysBaseAPI.getUserByName(username);
    if (user == null) {
        throw new AuthenticationException("用户不存在!");
    }
    // 判断用户状态
    if (user.getStatus() != 1) {
        throw new AuthenticationException("账号已被锁定,请联系管理员!");
    }
    // 校验token是否超时失效 & 或者账号密码是否错误
    if (!jwtTokenRefresh(token, username, user.getPassword(), redisUtil)) {
        throw new AuthenticationException("Token失效,请重新登录!");
    }
    return true;
}
 
源代码17 项目: jeecg-boot-with-activiti   文件: ShiroRealm.java
/**
 * 校验token的有效性
 *
 * @param token
 */
public LoginUser checkUserTokenIsEffect(String token) throws AuthenticationException {
	// 解密获得username,用于和数据库进行对比
	String username = JwtUtil.getUsername(token);
	if (username == null) {
		throw new AuthenticationException("token非法无效!");
	}

	// 查询用户信息
	log.info("———校验token是否有效————checkUserTokenIsEffect——————— "+ token);
       LoginUser loginUser = sysBaseAPI.getUserByName(username);
	if (loginUser == null) {
		throw new AuthenticationException("用户不存在!");
	}
       // 判断用户状态
       if (loginUser.getStatus() != 1) {
           throw new AuthenticationException("账号已被锁定,请联系管理员!");
       }
	// 校验token是否超时失效 & 或者账号密码是否错误
	if (!jwtTokenRefresh(token, username, loginUser.getPassword())) {
		throw new AuthenticationException("Token失效,请重新登录!");
	}

	return loginUser;
}
 
源代码18 项目: SpringAll   文件: ShiroRealm.java
/**
 * 登录认证
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	String userName = (String) token.getPrincipal();
	String password = new String((char[]) token.getCredentials());

	System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
	User user = userMapper.findByUserName(userName);

	if (user == null) {
		throw new UnknownAccountException("用户名或密码错误!");
	}
	if (!password.equals(user.getPassword())) {
		throw new IncorrectCredentialsException("用户名或密码错误!");
	}
	if (user.getStatus().equals("0")) {
		throw new LockedAccountException("账号已被锁定,请联系管理员!");
	}
	SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
	return info;
}
 
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
	assertRealmsConfigured();
	List<Realm> realms = this.getRealms()
		.stream()
		.filter(realm -> {
				return realm.supports(authenticationToken);
		})
		.collect(toList());
	if (CollectionUtils.isEmpty(realms)) 
		throw new IllegalStateException("Configuration error:  No realms support token type:" + authenticationToken.getClass());
	
	if (realms.size() == 1) {
		return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
	} else {
		return doMultiRealmAuthentication(realms, authenticationToken);
	}
}
 
源代码20 项目: sdb-mall   文件: OAuth2Filter.java
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    httpResponse.setContentType("application/json;charset=utf-8");
    httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
    httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
    try {
        //处理登录失败的异常
        Throwable throwable = e.getCause() == null ? e : e.getCause();
        R r = R.error(HttpStatus.SC_UNAUTHORIZED, throwable.getMessage());

        String json = new Gson().toJson(r);
        httpResponse.getWriter().print(json);
    } catch (IOException e1) {

    }

    return false;
}
 
源代码21 项目: java-platform   文件: DatabaseRealm.java
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	if (token instanceof UsernamePasswordToken) {
		String username = ((UsernamePasswordToken) token).getUsername();
		char[] password = ((UsernamePasswordToken) token).getPassword();

		if (Strings.isNullOrEmpty(username) || password == null) {
			return null;
		}

		User user = userRepository.findByUsername(username);
		if (user == null) {
			throw new UnknownAccountException();
		}

		return new SimpleAuthenticationInfo(new Principal(user.getId(), username), user.getPassword(), new SimpleByteSource(user.getUsername()),
				getName());
	}
	return null;
}
 
源代码22 项目: arcusplatform   文件: WebRunHandler.java
@Override
public FullHttpResponse respond(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
	Client client = factory.get(ctx.channel());
	RequestInfo info = parseUrl(req, PATH);
	if(StringUtils.isEmpty(info.getToken())) {
		throw new HttpException(HttpResponseStatus.BAD_REQUEST, "Missing token");
	}
	try {
		AppHandoffToken authenticationToken = new AppHandoffToken(info.getToken());
		authenticationToken.setHost(((InetSocketAddress) ctx.channel().remoteAddress()).getHostString());
		authenticationToken.setRememberMe(true);
		client.login(authenticationToken);
		
		FullHttpResponse response = redirect(info.toQueryString(webUrl).toString());
		DefaultCookie cookie = authenticator.createCookie(client.getSessionId());
		response.headers().set(HttpHeaders.Names.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
		return response;
	}
	catch(AuthenticationException e) {
		logger.debug("Failed to authenticate token, redirecting to web anyway");
		return redirect(info.toQueryString(webUrl).toString());
	}
}
 
源代码23 项目: flash-waimai   文件: ApiRealm.java
/**
 * 默认使用此方法进行用户名正确与否验证,错误抛出异常即可。
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
    String token = (String) auth.getCredentials();
    // 解密获得username,用于和数据库进行对比
    String username = JwtUtil.getUsername(token);
    if (username == null) {
        throw new AuthenticationException("token invalid");
    }

    ShiroUser userBean =  ShiroFactroy.me().shiroUser(userService.findByAccount(username));
    if (userBean == null) {
        throw new AuthenticationException("User didn't existed!");
    }

    if (! JwtUtil.verify(token, username, userBean.getPassword())) {
        throw new AuthenticationException("Username or password error");
    }

    return new SimpleAuthenticationInfo(token, token, "my_realm");
}
 
源代码24 项目: dubai   文件: ShiroDbRealm.java
/**
 * 认证回调函数,登录时调用.
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
       try{
           UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
           User user = userService.findUserByLoginName(token.getUsername());
           if (user != null && user.getStatusCode() == UserStatus.Active.code()) {
               byte[] salt = Encodes.decodeHex(user.getSalt());
               return new SimpleAuthenticationInfo(new ShiroUser(user.getId(), user.getLoginName(), user.getNiceName()),
                       user.getPassword(), ByteSource.Util.bytes(salt), getName());
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
       return null;
}
 
源代码25 项目: civism-sso   文件: UpmsRealm.java
/**
 * 认证信息,主要针对用户登录,
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    SsoUserNameToken ssoUserNameToken = (SsoUserNameToken) authenticationToken;
    LoginEntity loginEntity = ssoUserNameToken.getLoginEntity();
    UserInfo userInfo = null;
    try {
        userInfo = userService.login(loginEntity);
        Serializable id = SecurityUtils.getSubject().getSession().getId();
        userInfo.setToken((String) id);
        redisClient.set((String) id, SerializeUtil.serialize(userInfo), SsoConstants.DEFAULT_LOGIN_EXPIRE);
    } catch (CivismException e) {
        throw new CustomAccountException(e.getErrorCode());
    }
    return new SimpleAuthenticationInfo(userInfo, userInfo.getToken(), getName());
}
 
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
	Subject subject = getSubject(request, response); 
	if ((null == subject || !subject.isAuthenticated()) && isHmacSubmission(request)) {
		AuthenticationToken token = createHmacToken(request, response);
		try {
			subject = getSubject(request, response);
			subject.login(token);
			return this.checkRoles(subject,mappedValue);
		} catch (AuthenticationException e) {
			LOGGER.error(request.getRemoteHost()+" HMAC鉴权  "+e.getMessage());
			CommonUtils.restFailed(WebUtils.toHttp(response)
									,ShiroProperties.REST_CODE_AUTH_UNAUTHORIZED,e.getMessage());
		}	
	}
	return false;
}
 
/**
 * 登录表单提交
 *
 * @param jsonObject
 * @return
 */
@Override
public JSONObject authLogin(JSONObject jsonObject) {
    String username = jsonObject.getString("username");
    String password = jsonObject.getString("password");
    JSONObject returnData = new JSONObject();
    Subject currentUser = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);
    try {
        currentUser.login(token);
        returnData.put("result", "success");
    } catch (AuthenticationException e) {
        returnData.put("result", "fail");
    }
    return CommonUtil.successJson(returnData);
}
 
源代码28 项目: renren-fast   文件: OAuth2Filter.java
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    httpResponse.setContentType("application/json;charset=utf-8");
    try {
        //处理登录失败的异常
        Throwable throwable = e.getCause() == null ? e : e.getCause();
        R r = R.error(HttpStatus.SC_UNAUTHORIZED, throwable.getMessage());

        String json = new Gson().toJson(r);
        httpResponse.getWriter().print(json);
    } catch (IOException e1) {

    }

    return false;
}
 
源代码29 项目: hdw-dubbo   文件: JwtFilter.java
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    httpResponse.setContentType("application/json;charset=utf-8");
    httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
    httpResponse.setHeader("Access-Control-Allow-Origin", httpRequest.getHeader("Origin"));
    try {
        //处理登录失败的异常
        Throwable throwable = e.getCause() == null ? e : e.getCause();

        Map<String, Object> par = new HashMap<>();
        par.put("code", HttpStatus.SC_UNAUTHORIZED);
        par.put("msg", throwable.getMessage());

        httpResponse.getWriter().print(JacksonUtil.toJson(par));
    } catch (IOException e1) {
        e1.getStackTrace();
    }

    return false;
}
 
源代码30 项目: emodb   文件: ApiKeyRealm.java
/**
 * Gets the AuthenticationInfo that matches a token.  This method is only called if the info is not already
 * cached by the realm, so this method does not need to perform any further caching.
 */
@SuppressWarnings("unchecked")
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
        throws AuthenticationException {
    String id;

    if (AnonymousToken.isAnonymous(token)) {
        // Only continue if an anonymous identity has been set
        if (_anonymousId != null) {
            id = _anonymousId;
        } else {
            return null;
        }
    } else {
        id = ((ApiKeyAuthenticationToken) token).getPrincipal();
    }

    return getUncachedAuthenticationInfoForKey(id);
}