spring-security-oauth2 登录或者认证成功后 做一些操作, 比如登录日志。

通过跟踪代码,发现放当我们访问/oauth/token (这个请求的方法在TokenEndpoint)获取access_token 的时候,身份认证成功后会在 ProviderManager的authenticate 方法 通过eventPublisher.publishAuthenticationSuccess(result);
推出了一个认证成功的事件。

这样我们可以通过注册一个监听AuthenticationSuccessEvent事件的类, 对认证成功后 作出一些处理。
注意的是这个事件源可能有2种情况:
1.通过用户名密码校验身份的事件源(UsernamePasswordAuthenticationToken)
2.根据access_token校验 是否有效token的的事件源(OAuth2Authentication)


@Component
public class AuthenticationSuccessEventListener implements ApplicationListener<AuthenticationSuccessEvent> {

    @Autowired
    private LogService logService;

    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        //这里的事件源除了登录事件(UsernamePasswordAuthenticationToken)还有可能是token验证事件源(OAuth2Authentication)
        if(!event.getSource().getClass().getName().equals("org.springframework.security.authentication.UsernamePasswordAuthenticationToken")){
            return ;
        }
 		
 		 //这里还有oAuth2的客户端认证的事件,需要做一个判断
        if(event.getAuthentication().getDetails() != null){
        //登录日志逻辑。。。
        }
    }
}



部分源码–访问/oauth/token的入口

@FrameworkEndpoint
public class TokenEndpoint extends AbstractEndpoint {

	private OAuth2RequestValidator oAuth2RequestValidator = new DefaultOAuth2RequestValidator();

	private Set<HttpMethod> allowedRequestMethods = new HashSet<HttpMethod>(Arrays.asList(HttpMethod.POST));

	@RequestMapping(value = "/oauth/token", method=RequestMethod.GET)
	public ResponseEntity<OAuth2AccessToken> getAccessToken(Principal principal, @RequestParam
	Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
		
	}
	
	@RequestMapping(value = "/oauth/token", method=RequestMethod.POST)
	public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam
	Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {


	}

部分源码–推出 认证成功事件 -eventPublisher.publishAuthenticationSuccess(result);


public class ProviderManager implements AuthenticationManager, MessageSourceAware,
		InitializingBean {

public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		Class<? extends Authentication> toTest = authentication.getClass();
		AuthenticationException lastException = null;
		Authentication result = null;
		boolean debug = logger.isDebugEnabled();

		for (AuthenticationProvider provider : getProviders()) {
			if (!provider.supports(toTest)) {
				continue;
			}

			if (debug) {
				logger.debug("Authentication attempt using "
						+ provider.getClass().getName());
			}

			try {
				result = provider.authenticate(authentication);

				if (result != null) {
					copyDetails(authentication, result);
					break;
				}
			}
			catch (AccountStatusException e) {
				prepareException(e, authentication);
				// SEC-546: Avoid polling additional providers if auth failure is due to
				// invalid account status
				throw e;
			}
			catch (InternalAuthenticationServiceException e) {
				prepareException(e, authentication);
				throw e;
			}
			catch (AuthenticationException e) {
				lastException = e;
			}
		}

		if (result == null && parent != null) {
			// Allow the parent to try.
			try {
				result = parent.authenticate(authentication);
			}
			catch (ProviderNotFoundException e) {
				// ignore as we will throw below if no other exception occurred prior to
				// calling parent and the parent
				// may throw ProviderNotFound even though a provider in the child already
				// handled the request
			}
			catch (AuthenticationException e) {
				lastException = e;
			}
		}

		if (result != null) {
			if (eraseCredentialsAfterAuthentication
					&& (result instanceof CredentialsContainer)) {
				// Authentication is complete. Remove credentials and other secret data
				// from authentication
				((CredentialsContainer) result).eraseCredentials();
			}

			eventPublisher.publishAuthenticationSuccess(result);
			return result;
		}

		// Parent was null, or didn't authenticate (or throw an exception).

		if (lastException == null) {
			lastException = new ProviderNotFoundException(messages.getMessage(
					"ProviderManager.providerNotFound",
					new Object[] { toTest.getName() },
					"No AuthenticationProvider found for {0}"));
		}

		prepareException(lastException, authentication);

		throw lastException;
	}
}
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
你好!关于Spring Security OAuth2偶发性登录失败的问题,可能有多种原因导致。以下是一些常见的解决方案和调试步骤,供参考: 1. 检查授权服务器配置:确保你的授权服务器配置正确,并且与客户端应用程序的配置一致。检查授权服务器日志以获取任何错误消息或异常。 2. 检查令牌端点:确保令牌端点的URL和参数正确配置,并且与授权服务器的规范一致。检查令牌端点的请求和响应,以确定是否有任何问题。 3. 检查用户认证:确保用户认证机制正确配置,并且与授权服务器的规范一致。验证用户的凭据和身份验证流程是否正确。 4. 检查客户端凭证:确保客户端凭证(Client Credentials)正确配置,并且与授权服务器的规范一致。验证客户端凭证是否有效,并且具有适当的范围和权限。 5. 检查网络连接:偶发性登录失败可能与网络连接问题有关。检查网络连接是否稳定,并且没有阻止或限制请求的防火墙或代理。 6. 调试日志:在Spring Security配置中启用调试日志,以捕获更多详细信息。查看日志以获取任何异常、错误或警告消息。 7. 测试工具:使用Postman或似的工具测试授权服务器和令牌端点。确保请求和响应正常,并且没有任何问题。 如果以上步骤都没有解决问题,请提供更多详细信息,例如错误消息、日志输出或代码片段,以便我们更好地帮助你解决问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值