Spring cloud security oauth 2構築


簡単な説明
mysqlに基づいてclientクライアント情報を格納し、jwtに基づいてtokenを生成し、redisに基づいてtokenを格納し、認証ライセンスリソースサーバはゲートウェイにある
pom.xml構成

        org.springframework.boot
        spring-boot-starter-parent
        2.1.0.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
        Greenwich.M1
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

    
        org.springframework.cloud
        spring-cloud-starter-oauth2
        
            
                org.springframework.security.oauth
                spring-security-oauth2
            
        
    
    
    
        org.springframework.security.oauth
        spring-security-oauth2
        2.3.3.RELEASE
    
    
        org.springframework.cloud
        spring-cloud-starter-security
    


SecurityConfiguration.java
package zzq.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import zzq.security.entity.BaseUserDetailService;

/**
 * 〈    〉
* 〈 〉 * * @author zhouzhiqiang * @create 2018/11/18 0018 */ @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Bean @Override protected UserDetailsService userDetailsService() { return new BaseUserDetailService(); } /** * , , */ @Bean PasswordEncoder passwordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); } /** * , SpringBoot AuthenticationManager, */ @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { AuthenticationManager manager = super.authenticationManagerBean(); return manager; } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/","/home","/login","/oauth/**","/auth/**").permitAll() .antMatchers(HttpMethod.OPTIONS).permitAll() .anyRequest().authenticated() .and().formLogin().loginPage("/login") .failureHandler((req,resp,auth)->{ resp.sendRedirect("/login?error"); }) .successHandler((req, resp, auth) -> { resp.sendRedirect("/home"); }) .and().logout().logoutUrl("/logout") .logoutSuccessHandler((req, resp, auth) -> { resp.sendRedirect("/login"); }) .and().csrf().disable(); } }

ResourceServerConfiguration.java
package zzq.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * 〈    〉
* 〈 〉 * * @author zhouzhiqiang * @create 2018/11/18 0018 */ @Configuration @EnableResourceServer public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { @Override public void configure(ResourceServerSecurityConfigurer resources) { // stateless, accessToken session id , accessToken resources.resourceId("admin").stateless(true); } @Override public void configure(HttpSecurity http) throws Exception { http.antMatcher("/admin/**")// .authorizeRequests() .antMatchers(HttpMethod.OPTIONS).permitAll() .anyRequest().authenticated(); } }

AuthorizationServerConfiguration.java
package zzq.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.sql.DataSource;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 〈    〉
* 〈 〉 * * @author zhouzhiqiang * @create 2018/11/18 0018 */ @Configuration @EnableAuthorizationServer public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { @Autowired AuthenticationManager authenticationManager; @Autowired RedisConnectionFactory redisConnectionFactory; @Autowired private DataSource dataSource; @Bean public ClientDetailsService clientDetails() { return new JdbcClientDetailsService(dataSource); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { // jdbc clients.withClientDetails(clientDetails()); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) { endpoints .tokenStore(new RedisTokenStore(redisConnectionFactory)) .authenticationManager(authenticationManager) .accessTokenConverter(accessTokenConverter()) .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST); } @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) { // oauthServer.allowFormAuthenticationForClients(); } /** * JWT token Converter * @return */ @Bean public JwtAccessTokenConverter accessTokenConverter() { JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter() { /*** * token , token */ @Override public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { Authentication userAuthentication = authentication.getUserAuthentication(); String userName = null; Collection roles = null; if(userAuthentication != null){//grant_type client_credentials , userName = authentication.getUserAuthentication().getName(); User user = (User) authentication.getUserAuthentication().getPrincipal(); roles = user.getAuthorities(); } // /** token ***/ final Map additionalInformation = new HashMap<>(); additionalInformation.put("userName", userName); additionalInformation.put("roles", roles); ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation); OAuth2AccessToken enhancedToken = super.enhance(accessToken, authentication); return enhancedToken; } }; // , , RSA accessTokenConverter.setSigningKey("123"); return accessTokenConverter; } }

BaseUserDetailService.java
package zzq.security.entity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import zzq.rpc.UserService;
import zzq.utils.R;

import java.util.List;
import java.util.Map;

/**
 * 〈    〉
* 〈 Service〉 * * @author zhouzhiqiang * @create 2018-11-22 */ public class BaseUserDetailService implements UserDetailsService { @Autowired UserService us; @Autowired PasswordEncoder passwordEncoder; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { R r = us.findByUsername(username); Map userMap = (Map)r.get("user"); List authoritys = AuthorityUtils.createAuthorityList(); authoritys.add(new SimpleGrantedAuthority("user")); return new User(userMap.get("username"),userMap.get("password"),authoritys); } }

ソースアドレス:https://github.com/18770911080/zzq/tree/master/spring-cloud-zuul