SpringCloud oauth2 jwt gateway demo


前言

uaa 認證服務


@Configuration @EnableAuthorizationServer @AllArgsConstructor public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("user-service") .secret("123456") .scopes("service") .autoApprove(true) .authorizedGrantTypes("implicit", "refresh_token", "password", "authorization_code") .accessTokenValiditySeconds(12 * 300);//5min過期 } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.tokenStore(tokenStore()).tokenEnhancer(jwtTokenEnhancer()).authenticationManager(authenticationManager); } @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer .tokenKeyAccess("permitAll()") .checkTokenAccess("isAuthenticated()").allowFormAuthenticationForClients().passwordEncoder(NoOpPasswordEncoder.getInstance()); /** * 必須設置allowFormAuthenticationForClients 否則沒有辦法用postman獲取token * 也需要指定密碼加密方式BCryptPasswordEncoder */ } @Autowired @Qualifier("authenticationManagerBean") private AuthenticationManager authenticationManager; @Bean public TokenStore tokenStore() { return new JwtTokenStore(jwtTokenEnhancer()); } @Bean protected JwtAccessTokenConverter jwtTokenEnhancer() { JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter(); jwtAccessTokenConverter.setKeyPair(keyPair()); return jwtAccessTokenConverter; } @Bean public KeyPair keyPair() { KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("demojwt.jks"), "keystorepass".toCharArray()); return keyStoreKeyFactory.getKeyPair("jwt", "keypairpass".toCharArray()); }

uaa websecurityconfig

@Configuration class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity http) throws Exception {   http.csrf().disable() .exceptionHandling() .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED)) .and() .authorizeRequests() .antMatchers("/.well-known/jwks.json").permitAll() .antMatchers("/**").authenticated() .and() .httpBasic(); } @Autowired UserServiceDetail userServiceDetail; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userServiceDetail) .passwordEncoder(new BCryptPasswordEncoder()); } } 

資源服務配置

@EnableWebFluxSecurity public class SecurityConfig { @Bean SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) throws Exception { http .authorizeExchange() .pathMatchers("/**").authenticated() .anyExchange() .authenticated() .and() .oauth2ResourceServer() .jwt(); return http.build(); } } 

網關配置

@SpringBootApplication @EnableEurekaClient public class GatewayServiceApplication { public static void main(String[] args) { SpringApplication.run(GatewayServiceApplication.class, args); } @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { return builder.routes() .route("resource", r -> r.path("/resource/**") .filters(f -> f.stripPrefix(1))//去掉第一層前綴如果是/api/oauth這種 就stripPrefix(2) .uri("lb://resource-service")) // Prevents cookie being sent downstream // .uri("http://localhost:9090")) // Taking advantage of docker naming .route("uaa",r -> r.path("/uaa/**") .filters(f -> f.stripPrefix(1)) .uri("lb://uaa-service")) .build(); } } 

演示

直接授權

http://localhost:9999/oauth/token?client_id=user-service&client_secret=123456&grant_type=password&username=wenx&password=admin

 
 

訪問開放資源

http://localhost:9090/hello

 
 

訪問需要授權

 
 

帶上token訪問

 
 

經過網關轉發授權

http://localhost:8068/uaa/oauth/token?client_id=user-service&client_secret=123456&grant_type=password&username=wenx&password=admin

 
 

經過網關訪問開發資源

http://localhost:8068/resource/hello

 
 

經過網關訪問授權資源

http://localhost:8068/resource/foo

 
 

帶上token訪問授權資源

http://localhost:8068/resource/foo

 
 
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM