Spring Boot Oauth2

Spring Boot Oauth2

pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security.oauth.boot</groupId>
    <artifactId>spring-security-oauth2-autoconfigure</artifactId>
    <version>2.0.1.RELEASE</version>
</dependency>
资源服务和认证服务

SecurityConfiguration

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String finalPassword = bCryptPasswordEncoder.encode("user");
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("user").password(finalPassword).authorities("USER").build());
        return manager;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
                .and().formLogin().permitAll()
                .and().logout().permitAll();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

创建Oauth2Configuration配置认证服务和资源服务

@Configuration
public class Oauth2Configuration {

@Configuration
public class Oauth2Configuration {

    private static final String DEMO_RESOURCE_ID = "order";

    @Configuration
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            resources.resourceId(DEMO_RESOURCE_ID).stateless(false);
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                    .and().antMatcher("/user").authorizeRequests().anyRequest().authenticated();
        }
    }


    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        @Autowired
        private AuthenticationManager authenticationManager;
        @Autowired
        private PasswordEncoder passwordEncoder;

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.inMemory().withClient("client")
                    .resourceIds(DEMO_RESOURCE_ID)
                    .authorizedGrantTypes("authorization_code", "refresh_token")
                    .scopes("user")
                    .secret(passwordEncoder.encode("secret"))
                    .autoApprove(true);
        }

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
            endpoints.authenticationManager(authenticationManager)
                    .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
        }

        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
            oauthServer.allowFormAuthenticationForClients().tokenKeyAccess("permitAll()")
                    .checkTokenAccess("isAuthenticated()");
        }

    }
}

application.yml

server:
  port: 8081
  servlet:
    session:
      cookie:
        name: JSID
logging:
  level:
    org.springframework.security: debug

启动类

@SpringBootApplication
@EnableResourceServer
public class ServerApp {

    public static void main(String[] args) {
        SpringApplication.run(ServerApp.class, args);
    }

    @RestController
    class UserController {
        @GetMapping("/user")
        public Principal user(Principal user) {
            return user;
        }
    }
}
创建客户端

application.yml

server:
    port: 8083
security:
  oauth2:
    client:
      clientId: client
      clientSecret: secret
      accessTokenUri: http://localhost:8081/oauth/token
      userAuthorizationUri: http://localhost:8081/oauth/authorize
      scope: user
    resource:
      userInfoUri: http://localhost:8081/user
      token-info-uri: http://localhost:8081/oauth/check_token
logging:
  level:
    org.springframework.security: debug

启动类

@SpringBootApplication
@EnableOAuth2Sso
public class ClientApp {

    public static void main(String[] args) {
        SpringApplication.run(ClientApp.class, args);
    }

    @RestController
    class UserController {
        @GetMapping("/")
        public Principal user(Principal principal) {
            return principal;
        }
    }

}

猜你喜欢

转载自blog.csdn.net/lht931942788/article/details/80400641