springcloud + zuul + oauth2 implement unified authentication service

The first configuration: zuul only responsible for forwarding, flow control, etc. (not responsible for certification)

1 Introduction

(1) eureka discovery service, each service is configured not made, just look on this certification;

2 Configure the authentication server

(1) add a dependency (OAuth already contains security)

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>

  

(2) Authentication Configuration

@Configuration 
public class MyConfig { 
 
    // set the user information processing type, here 123, a user name a password in order to test arbitrarily 
    @Component 
    public static class myUserDetailsService the implements the UserDetailsService { 
        @Autowired 
        Private The PasswordEncoder PasswordEncoder; 
 
        @Override 
        public the UserDetails loadUserByUsername (String username) throws UsernameNotFoundException { 
            return new new the User (username, passwordEncoder.encode ( "123"), 
                    AuthorityUtils.commaSeparatedStringToAuthorityList ( "users with the ROLE_USER")); 
        } 
    } 
 
    // authentication server 
    @EnableAuthorizationServer 
    @Configuration 
    public static class the extends the Authorization {AuthorizationServerConfigurerAdapter
 
        @Autowired 
        the AuthenticationManager the authenticationManager; 
        @Autowired 
        BCryptPasswordEncoder bCryptPasswordEncoder; 
        @Autowired 
        myUserDetailsService myUserDetailsService; 
 
        // To test client certificate stored in the memory (of production should be used to store the database, oauth standard database templates) 
        @Override 
        public void the configure (ClientDetailsServiceConfigurer Clients) throws {Exception 
            clients.inMemory () 
                    .withClient ( "client") // client_id 
        } 
                    .secret (bCryptPasswordEncoder.encode ( "123")) // client_secret
                    .authorizedGrantTypes ( "authorization_code", "password ") // allows the client license type 
                    .scopes ( "app"); // allow mandates 
        public void configure (AuthorizationServerSecurityConfigurer Security) throws Exception {
 
        // authenticationManager use with the password mode, tokenstore available production Redis 
        @Override 
        public void Configure (AuthorizationServerEndpointsConfigurer Endpoints) throws Exception { 
            endpoints.authenticationManager (the authenticationManager) 
                    .tokenStore (new new InMemoryTokenStore ()) 
                    .userDetailsService (myUserDetailsService); 
        } 
 
        // token configuration state query 
        @Override 
            security.tokenKeyAccess ( "permitAll ()"); 
            security.checkTokenAccess ( "isAuthenticated ()"); 
        } 
    } 
 
    // use an authentication server must comply with Security 
    @Configuration
    public static class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Bean
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }
 
        @Bean
        public BCryptPasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
 
        //这里只验证是否带有token的失败返回authenticationEntryPoint
        @Override
        Configure void protected (HttpSecurity HTTP) throws Exception { 
            HTTP 
                    .httpBasic () and (). 
                    .csrf().disable()
                    .exceptionHandling()
                    .authenticationEntryPoint ((REQ, RESP, Exception) -> { 
                        resp.setContentType (MediaType.APPLICATION_JSON_UTF8_VALUE); 
                        . resp.getWriter () Write (new new ObjectMapper () writeValueAsString. (new new the HashMap () {{ 
                            PUT ( "Status", 0); 
                            PUT ( "error", "no authority"); 
                        }})); 
                    .}) and () 
             .authorizeRequests () anyRequest. () .authenticated (); 
        } 
    } 
 
    // resource allocation processor, in order to access the other clients user login information and the like
    @Configuration
    @EnableResourceServer
    public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.csrf().disable().exceptionHandling().authenticationEntryPoint((req, resp, exception) -> {
                resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                resp.getWriter().write(new ObjectMapper().writeValueAsString(new HashMap() {{
                    put("status", 0);
                    put("error", "没有权限");
                }}));
            }).and().authorizeRequests().anyRequest().authenticated();
        }
    }
}

  

(3) provide customer information

@RestController 
public class ResourceWeb { 
 
    @GetMapping ( "/ Member") 
    public the Principal User (the Principal Member) { 
        // get the current user information 
        return Member; 
    } 
}

(4) Process

  Here is the password, the general service for local calls itself the resources;

  (Client, secret) on behalf of a client account password, in this test, the client actually says that if local service is a third party, the latter apply to the account password, you can get the resources to call upon user authorization.;

  (Username, password) is the main user of this service, all clients access to resources requires a local user login before they get after a successful authorization, the use of landing security strategy;

 

3. Configure the resource server (local resources)

(1) Add the same dependency oauth

(2) configure remote authentication service:

security:
  oauth2:
    resource:
      user-info-uri: http://localhost:8082/member
      prefer-token-info: false

  

@Configuration
public class MyConfig {
 
    //配置资源服务器
    @Configuration
    @EnableResourceServer
    public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.csrf().disable().httpBasic().disable().exceptionHandling().authenticationEntryPoint((req, resp, exception) -> {
                resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                resp.getWriter().write(new ObjectMapper().writeValueAsString(new HashMap() {{
                    put("status", 0);
                    put("error", "没有权限");
                }}));
            })
            .and().authorizeRequests().antMatchers("/noauth").permitAll()
            .and().authorizeRequests().anyRequest().authenticated();
        }
    }
}

4. Configuration zuul

Zuul: 
  #routes: 
  # Mechant: 
  #-Service-ID: Mechant 
  # path: / Mechant / ** 
  Strip-prefix: when when true # false, the request address -> MECHANT-> http: // localhost : 8081 / api / mechant / ping, returned 404 
  prefix: / API request # prefix 
  sensitive-headers: # do not write here can not carry header; if the client request is made with the X-ABC, then the X-ABC will not be passed to downstream services 
  #ignoredHeaders: X-ABC # If the client request is made with the X-ABC, then the X-ABC will still be passed to downstream services. But if the downstream services will be filtered and then forwarded

  

5. Test

(1) application token (using zuul access)

(2) using the token (using zuul access)

 

Guess you like

Origin www.cnblogs.com/liboware/p/12528755.html