Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to integrate spring cloud gateway oauth

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces you how to carry out spring cloud gateway oauth integration, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Spring cloud gateway fine-grained configuration spring cloud oauth before and after separation project

Pom dependence

Org.springframework.boot spring-boot-starter-security org.springframework.security spring-security-oauth3-resource-server org.springframework.security.oauth spring-security-oauth3 org.springframework.boot spring-boot-starter-webflux org.springframework.cloud spring-cloud-starter-gateway

Simple check

/ * * Program name: AccessFilter Establishment date: 2018-09-09 author: someday Module: gateway description: oauth check remarks: * version20180909001 *

* change history serial number date modification reason * / @ Componentpublic class AccessFilter implements GlobalFilter, Ordered {/ / url matcher private AntPathMatcher pathMatcher = new AntPathMatcher (); @ Resource private RedisTemplate redisTemplate; @ Resource private AuthIgnored authIgnored; @ Override public int getOrder () {/ / TODO Auto-generated method stub return-500 } @ Override public Mono filter (ServerWebExchange exchange, GatewayFilterChain chain) {/ / TODO Auto-generated method stub String accessToken = TokenUtil.extractToken (exchange.getRequest ()); / / default boolean flag = false; for (String ignored: authIgnored.getIgnored ()) {if (pathMatcher.match (ignored, exchange.getRequest (). GetPath (). Value () {flag = true / / whitelist} if (flag) {return chain.filter (exchange);} else {Map params = (Map) redisTemplate.opsForValue (). Get (UaaConstant.TOKEN+ ":" + accessToken); if (params! = null) {return chain.filter (exchange) } else {exchange.getResponse (). SetStatusCode (HttpStatus.UNAUTHORIZED); ServerHttpResponse response = exchange.getResponse (); JSONObject message = new JSONObject (); message.put ("resp_code", 401); message.put ("resp_msg", "not certified!") ; byte [] bits = message.toJSONString () .getBytes (StandardCharsets.UTF_8); DataBuffer buffer = response.bufferFactory () .wrap (bits); response.setStatusCode (HttpStatus.UNAUTHORIZED); / / specify the code, otherwise response.getHeaders () .add ("Content-Type", "application/json;charset=UTF-8") will be garbled in the browser. Return response.writeWith (Mono.just (buffer));}

Configure the resource server

Package com.open.capacity.client.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.actuate.autoconfigure.security.reactive.EndpointRequest;import org.springframework.boot.context.properties.EnableConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.HttpMethod;import org.springframework.http.server.reactive.ServerHttpRequest;import org.springframework.security.authentication.ReactiveAuthenticationManager;import org.springframework.security.config.http.SessionCreationPolicy Import org.springframework.security.config.web.server.SecurityWebFiltersOrder;import org.springframework.security.config.web.server.ServerHttpSecurity;import org.springframework.security.oauth3.common.OAuth3AccessToken;import org.springframework.security.oauth3.provider.token.TokenStore;import org.springframework.security.web.server.SecurityWebFilterChain;import org.springframework.security.web.server.authentication.AuthenticationWebFilter;import org.springframework.web.server.WebFilter;import com.open.capacity.client.handler.ResAccessDeniedHandler;import com.open.capacity.client.handler.ResAuthenticationEntryPoint Import com.open.capacity.client.handler.ResAuthenticationFailureHandler;import com.open.capacity.client.handler.ResAuthenticationSuccessHandler;import com.open.capacity.client.token.AuthorizeConfigManager;import com.open.capacity.client.token.TokenAuthenticationConverter;import com.open.capacity.client.token.TokenAuthenticationManager;import com.open.capacity.common.auth.props.PermitUrlProperties;/** * Resource Server UAAClientAutoConfig * / @ Configuration@EnableConfigurationProperties (PermitUrlProperties.class) public class UAAClientAutoConfig {@ Autowired private PermitUrlProperties permitUrlProperties; @ Autowired private TokenStore tokenStore @ Autowired private AuthorizeConfigManager authorizeConfigManager; / / @ Resource (name= "delegatingAuthorizationManager") / / private DelegatingReactiveAuthorizationManager delegatingAuthorizationManager; @ Bean public SecurityWebFilterChain springSecurityFilterChain (ServerHttpSecurity http) {/ / authenticated processor ReactiveAuthenticationManager tokenAuthenticationManager = new TokenAuthenticationManager (tokenStore); ResAuthenticationEntryPoint resAuthenticationEntryPoint = new ResAuthenticationEntryPoint (); ResAccessDeniedHandler resAccessDeniedHandler = new ResAccessDeniedHandler () / / build Bearer Token / / request parameters are forced to add Authorization BEARER token http.addFilterAt ((WebFilter) (exchange, chain)-> {ServerHttpRequest request = exchange.getRequest () If (request.getQueryParams (). GetFirst ("access_token")! = null) {exchange.getRequest () .mutate () .headers (httpHeaders-> httpHeaders.add ("Authorization", OAuth3AccessToken.BEARER_TYPE+ "" + request.getQueryParams () .getFirst ("access_token") } return chain.filter (exchange);}, SecurityWebFiltersOrder.FIRST); / / Authentication AuthenticationWebFilter authenticationWebFilter = new AuthenticationWebFilter (tokenAuthenticationManager); authenticationWebFilter.setAuthenticationFailureHandler (new ResAuthenticationFailureHandler ()); / / login verification failed authenticationWebFilter.setAuthenticationSuccessHandler (new ResAuthenticationSuccessHandler ()); / / Authentication successful / / token converter TokenAuthenticationConverter tokenAuthenticationConverter = new TokenAuthenticationConverter (); tokenAuthenticationConverter.setAllowUriQueryParameter (true) AuthenticationWebFilter.setServerAuthenticationConverter (tokenAuthenticationConverter); http.addFilterAt (authenticationWebFilter, SecurityWebFiltersOrder.AUTHENTICATION); / / access authorization / / AuthorizationWebFilter authorizationWebFilter=new AuthorizationWebFilter (delegatingAuthorizationManager); / / http.addFilterAt (authorizationWebFilter, SecurityWebFiltersOrder.FORM_LOGIN); ServerHttpSecurity.AuthorizeExchangeSpec authorizeExchange = http.authorizeExchange (); authorizeExchange.matchers (EndpointRequest.toAnyEndpoint ()). PermitAll () / / request path authorizeExchange.pathMatchers (permitUrlProperties.getIgnored ()) .permitAll () without permission filtering / / request path authorizeExchange .pathMatrices (HttpMethod.OPTIONS) without permission filtering. PermitAll () / / option request default release / / .anyExchange () .access (authorizeConfigManager) / / apply api permission control .anyExchange () .pathMatrices () / / token validity control .and () .promotionHandling () .accessDeniedHandler (resAccessDeniedHandler) .authenticationEntryPoint (resAuthenticationEntryPoint) .and () .headers () .frameOptions () .disable () .and () .httpBasic () .disable () .csrf () .disable () Return http.build ();}}

Token validity period detection

Package com.open.capacity.client.token;import org.springframework.http.HttpStatus;/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "ASIS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * / import org.springframework.security.authentication.ReactiveAuthenticationManager;import org.springframework.security.core.Authentication;import org.springframework.security.oauth3.common.OAuth3AccessToken;import org.springframework.security.oauth3.common.exceptions.InvalidTokenException;import org.springframework.security.oauth3.core.OAuth3AuthenticationException;import org.springframework.security.oauth3.core.OAuth3Error;import org.springframework.security.oauth3.provider.OAuth3Authentication;import org.springframework.security.oauth3.provider.token.TokenStore;import org.springframework.security.oauth3.server.resource.BearerTokenAuthenticationToken Import org.springframework.security.oauth3.server.resource.BearerTokenError;import org.springframework.security.oauth3.server.resource.BearerTokenErrorCodes;import reactor.core.publisher.Mono;/** * A {@ link ReactiveAuthenticationManager} for Jwt tokens. * * @ author Rob Winch * @ since 5.1 * / public final class TokenAuthenticationManager implements ReactiveAuthenticationManager {private TokenStore tokenStore; public TokenAuthenticationManager (TokenStore tokenStore) {this.tokenStore = tokenStore } @ Override public Mono authenticate (Authentication authentication) {return Mono.justOrEmpty (authentication) .filter (a-> an instanceof BearerTokenAuthenticationToken) .cast (BearerTokenAuthenticationToken.class) .map (BearerTokenAuthenticationToken::getToken) .flatMap ((accessTokenValue-> {OAuth3AccessToken accessToken = tokenStore.readAccessToken (accessTokenValue)) If (accessToken = = null) {OAuth3Error error = new BearerTokenError (BearerTokenErrorCodes.INVALID_TOKEN, HttpStatus.UNAUTHORIZED, "Invalid access token:" + accessTokenValue) "https://tools.ietf.org/html/rfc6750#section-3.1"); Return Mono.error (new OAuth3AuthenticationException (error, "Invalid access token:" + accessTokenValue));} else if (accessToken.isExpired ()) {tokenStore.removeAccessToken (accessToken) OAuth3Error error = new BearerTokenError (BearerTokenErrorCodes.INVALID_TOKEN, HttpStatus.UNAUTHORIZED, "Access token expired:" + accessTokenValue, "https://tools.ietf.org/html/rfc6750#section-3.1");" Return Mono.error (new OAuth3AuthenticationException (error, "Access token expired:" + accessTokenValue));} OAuth3Authentication result = tokenStore.readAuthentication (accessToken); if (result = = null) {return Mono.error ("Invalid access token:" + accessTokenValue)) } return Mono.just (result);}) .cast (Authentication.class);}}

Apply accessible API list control

Package com.open.capacity.client.token;import java.util.Iterator;import java.util.List;import java.util.Map;import javax.annotation.Resource;import org.springframework.http.server.reactive.ServerHttpRequest;import org.springframework.security.authorization.AuthorizationDecision;import org.springframework.security.authorization.ReactiveAuthorizationManager;import org.springframework.security.core.Authentication;import org.springframework.security.oauth3.provider.OAuth3Authentication;import org.springframework.security.web.server.authorization.AuthorizationContext;import org.springframework.stereotype.Component;import org.springframework.util.AntPathMatcher Import org.springframework.web.server.ServerWebExchange;import com.open.capacity.client.dao.SysClientDao;import com.open.capacity.client.dao.SysServiceDao;import reactor.core.publisher.Mono;/** * @ author author owen E-mail: 624191343@qq.com * @ version creation time: 9:47:00 on February 1, 2018 Class description * / @ Componentpublic class AuthorizeConfigManager implements ReactiveAuthorizationManager {@ Resource private SysServiceDao sysServiceDao; @ Resource private SysClientDao sysClientDao; private AntPathMatcher antPathMatcher = new AntPathMatcher () @ Override public Mono check (Mono authentication, AuthorizationContext authorizationContext) {return authentication.map (auth-> {/ / TODO are currently true boolean hasPermission = false; ServerWebExchange exchange = authorizationContext.getExchange (); ServerHttpRequest request = exchange.getRequest (); if (auth instanceof OAuth3Authentication) {OAuth3Authentication athentication = (OAuth3Authentication) auth String clientId = athentication.getOAuth3Request (). GetClientId (); Map map = sysClientDao.getClient (clientId); if (map = = null) {return new AuthorizationDecision (false);} else {List list = sysServiceDao.listByClientId (Long.valueOf (String.valueOf (map.get ("id") For (Iterator it = list.iterator (); it.hasNext ();) {Map temp = it.next (); if (antPathMatcher.match (String.valueOf (temp.get ("path")), request.getURI (). GetPath ()) {return new AuthorizationDecision (true) }} return new AuthorizationDecision (false);}} / / boolean isPermission = super.hasPermission (auth, / / request.getMethodValue (), request.getURI (). GetPath ()); return new AuthorizationDecision (hasPermission);}) .defaultIfEmpty (new AuthorizationDecision (false)) }} on how to carry out spring cloud gateway oauth integration to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report