org.apache.shiro.authc.AuthenticationException Java Examples

The following examples show how to use org.apache.shiro.authc.AuthenticationException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ShiroRealm.java    From jeecg-boot-with-activiti with MIT License 6 votes vote down vote up
/**
 * 校验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;
}
 
Example #2
Source File: OpenIdConnector.java    From onedev with MIT License 6 votes vote down vote up
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);
}
 
Example #3
Source File: AuthRealm.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 认证(主要是用来进行身份认证的,也就是说验证用户输入的账号和密码是否正确)
 *
 * @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;
}
 
Example #4
Source File: ApiRealm.java    From web-flash with MIT License 6 votes vote down vote up
/**
 * 默认使用此方法进行用户名正确与否验证,错误抛出异常即可。
 */
@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");
}
 
Example #5
Source File: ShiroRealm.java    From SpringAll with MIT License 6 votes vote down vote up
/**
 * 登录认证
 */
@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;
}
 
Example #6
Source File: SysLoginController.java    From supplierShop with MIT License 6 votes vote down vote up
@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);
    }
}
 
Example #7
Source File: Oauth2SnsAuthorizingRealm.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #8
Source File: LdapRealm.java    From Moss with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #9
Source File: MyShiroRealm.java    From EasyReport with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #10
Source File: MyRealm.java    From MyBlog with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #11
Source File: LoginResource.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #12
Source File: LoginController.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 6 votes vote down vote up
@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);
    }
}
 
Example #13
Source File: SysLoginController.java    From ruoyiplus with MIT License 6 votes vote down vote up
@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);
    }
}
 
Example #14
Source File: ShiroRealm.java    From SpringAll with MIT License 6 votes vote down vote up
/**
 * 用户认证
 *
 * @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");
}
 
Example #15
Source File: TokenUtils.java    From jeecg-boot-with-activiti with MIT License 6 votes vote down vote up
/**
 * 验证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;
}
 
Example #16
Source File: UUserRealm.java    From cjs_ssms with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 登录认证,在权限认证前执行
 *
 * @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;
  }
}
 
Example #17
Source File: ShiroRealm.java    From SpringAll with MIT License 6 votes vote down vote up
/**
 * 登录认证
 */
@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;
}
 
Example #18
Source File: JsetsModularRealmAuthenticator.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
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);
	}
}
 
Example #19
Source File: OAuth2Filter.java    From sdb-mall with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #20
Source File: DatabaseRealm.java    From java-platform with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #21
Source File: WebRunHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@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());
	}
}
 
Example #22
Source File: ApiRealm.java    From flash-waimai with MIT License 6 votes vote down vote up
/**
 * 默认使用此方法进行用户名正确与否验证,错误抛出异常即可。
 */
@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");
}
 
Example #23
Source File: ShiroDbRealm.java    From dubai with MIT License 6 votes vote down vote up
/**
 * 认证回调函数,登录时调用.
 */
@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;
}
 
Example #24
Source File: UpmsRealm.java    From civism-sso with Apache License 2.0 6 votes vote down vote up
/**
 * 认证信息,主要针对用户登录,
 */
@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());
}
 
Example #25
Source File: HmacRolesFilter.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #26
Source File: LoginServiceImpl.java    From SpringBoot-Shiro-Vue-master-20180625 with Apache License 2.0 6 votes vote down vote up
/**
 * 登录表单提交
 *
 * @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);
}
 
Example #27
Source File: OAuth2Filter.java    From renren-fast with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #28
Source File: JwtFilter.java    From hdw-dubbo with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #29
Source File: ApiKeyRealm.java    From emodb with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #30
Source File: HmacPermsFilter.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@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.checkPerms(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;
}