Springsecurityoauth2的認證流程是什么

今天就跟大家聊聊有關Spring security oauth2的認證流程是什么,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據(jù)這篇文章可以有所收獲。

阜城網站制作公司哪家好,找成都創(chuàng)新互聯(lián)公司!從網頁設計、網站建設、微信開發(fā)、APP開發(fā)、響應式網站等網站項目制作,到程序開發(fā),運營維護。成都創(chuàng)新互聯(lián)公司成立于2013年到現(xiàn)在10年的時間,我們擁有了豐富的建站經驗和運維經驗,來保證我們的工作的順利進行。專注于網站建設就選成都創(chuàng)新互聯(lián)公司

Spring security oauth3資源的認證模式

ResourceServerSecurityConfigurer資源配置模式

@Override
	public void configure(HttpSecurity http) throws Exception {

		AuthenticationManager oauthAuthenticationManager = oauthAuthenticationManager(http);
		resourcesServerFilter = new OAuth3AuthenticationProcessingFilter();
		resourcesServerFilter.setAuthenticationEntryPoint(authenticationEntryPoint);
		resourcesServerFilter.setAuthenticationManager(oauthAuthenticationManager);
		if (eventPublisher != null) {
			resourcesServerFilter.setAuthenticationEventPublisher(eventPublisher);
		}
		if (tokenExtractor != null) {
		 //添加token的額外解析方法 默認調用BearerTokenExtractor
			resourcesServerFilter.setTokenExtractor(tokenExtractor);
		}
		if (authenticationDetailsSource != null) {
			resourcesServerFilter.setAuthenticationDetailsSource(authenticationDetailsSource);
		}
		resourcesServerFilter = postProcess(resourcesServerFilter);
		resourcesServerFilter.setStateless(stateless);

		// @formatter:off
		http
			.authorizeRequests().expressionHandler(expressionHandler)
		.and()
			.addFilterBefore(resourcesServerFilter, AbstractPreAuthenticatedProcessingFilter.class)
			.exceptionHandling()
				.accessDeniedHandler(accessDeniedHandler)
				.authenticationEntryPoint(authenticationEntryPoint);
		// @formatter:on
	}

OAuth3AuthenticationProcessingFilter中作為filter攔截認證會借助tokenExtractor從request中獲取token的值,將其轉換為Authentication 對象。

public class OAuth3AuthenticationProcessingFilter implements Filter, InitializingBean {
...
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
			ServletException {

		final boolean debug = logger.isDebugEnabled();
		final HttpServletRequest request = (HttpServletRequest) req;
		final HttpServletResponse response = (HttpServletResponse) res;

		try {
//調用TokenExtractor從httpRequest解析出對應的token值,將其轉化為Authentication對象。
			Authentication authentication = tokenExtractor.extract(request);
			
			if (authentication == null) {
				if (stateless && isAuthenticated()) {
					if (debug) {
						logger.debug("Clearing security context.");
					}
					SecurityContextHolder.clearContext();
				}
				if (debug) {
					logger.debug("No token in request, will continue chain.");
				}
			}
			else {
				request.setAttribute(OAuth3AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
				if (authentication instanceof AbstractAuthenticationToken) {
					AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
					needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));
				}
//2調用的Authenticationd對象,調用authenticationManager.authenticate的方法
來判斷用戶是否登陸成功
				Authentication authResult = authenticationManager.authenticate(authentication);

				if (debug) {
					logger.debug("Authentication success: " + authResult);
				}

				eventPublisher.publishAuthenticationSuccess(authResult);
				SecurityContextHolder.getContext().setAuthentication(authResult);

			}
		}
		catch (OAuth3Exception failed) {
			SecurityContextHolder.clearContext();

			if (debug) {
				logger.debug("Authentication request failed: " + failed);
			}
			eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed),
					new PreAuthenticatedAuthenticationToken("access-token", "N/A"));

			authenticationEntryPoint.commence(request, response,
					new InsufficientAuthenticationException(failed.getMessage(), failed));

			return;
		}

		chain.doFilter(request, response);
	}
}
....
}

認證執(zhí)行結束之后,繼續(xù)走configure中的配置的權限認證過濾操作 AuthenticationManager 默認實現(xiàn)方式是配置的OAuth3AuthenticationManager,所以OAuth3AuthenticationManager中的

--ResourceServerSecurityConfigurer.java
private AuthenticationManager oauthAuthenticationManager(HttpSecurity http) {
		OAuth3AuthenticationManager oauthAuthenticationManager = new OAuth3AuthenticationManager();
		if (authenticationManager != null) {
			if (authenticationManager instanceof OAuth3AuthenticationManager) {
				oauthAuthenticationManager = (OAuth3AuthenticationManager) authenticationManager;
			}
			else {
				return authenticationManager;
			}
		}
		oauthAuthenticationManager.setResourceId(resourceId);
//配置tokenService解析方式		oauthAuthenticationManager.setTokenServices(resourceTokenServices(http));
		oauthAuthenticationManager.setClientDetailsService(clientDetails());
		return oauthAuthenticationManager;
	}

private ResourceServerTokenServices resourceTokenServices(HttpSecurity http) {
		tokenServices(http);
		return this.resourceTokenServices;
	}

	private ResourceServerTokenServices tokenServices(HttpSecurity http) {
		if (resourceTokenServices != null) {
			return resourceTokenServices;
		}
		DefaultTokenServices tokenServices = new DefaultTokenServices();
		//指定token的解析方式
		tokenServices.setTokenStore(tokenStore());
		tokenServices.setSupportRefreshToken(true);
		tokenServices.setClientDetailsService(clientDetails());
		this.resourceTokenServices = tokenServices;
		return tokenServices;
	}

Token的存取模式:

種模式

  • InMemoryTokenStore

  • JdbcTokenStore

  • JwtTokenStore

  • JwkTokenStore

  • redisTokenStore

--OAuth3AuthenticationManager認證管理
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {

		if (authentication == null) {
			throw new InvalidTokenException("Invalid token (token not found)");
		}
		String token = (String) authentication.getPrincipal();
//從指定的實現(xiàn)的tokenStore中獲取對應的值
		OAuth3Authentication auth = tokenServices.loadAuthentication(token);
		if (auth == null) {
			throw new InvalidTokenException("Invalid token: " + token);
		}

		Collection<String> resourceIds = auth.getOAuth3Request().getResourceIds();
		if (resourceId != null && resourceIds != null && !resourceIds.isEmpty() && !resourceIds.contains(resourceId)) {
			throw new OAuth3AccessDeniedException("Invalid token does not contain resource id (" + resourceId + ")");
		}

		checkClientDetails(auth);

		if (authentication.getDetails() instanceof OAuth3AuthenticationDetails) {
			OAuth3AuthenticationDetails details = (OAuth3AuthenticationDetails) authentication.getDetails();
			// Guard against a cached copy of the same details
			if (!details.equals(auth.getDetails())) {
				// Preserve the authentication details from the one loaded by token services
				details.setDecodedDetails(auth.getDetails());
			}
		}
		auth.setDetails(authentication.getDetails());
		auth.setAuthenticated(true);
		return auth;

	}

看完上述內容,你們對Spring security oauth2的認證流程是什么有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。

文章名稱:Springsecurityoauth2的認證流程是什么
文章起源:http://muchs.cn/article28/jpjocp.html

成都網站建設公司_創(chuàng)新互聯(lián),為您提供品牌網站設計、做網站網站制作、外貿建站面包屑導航、移動網站建設

廣告

聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

小程序開發(fā)