spring cloud oauth2 密码认证


spring cloud oauth2 密码认证

*****************************

认证服务器:authorization-server

*********************

配置文件

spring:
  application:
    name: authorization-server

server:
  port: 8081

*********************

service 层

UserService:读取内存中的用户

@Service
public class UserService implements UserDetailsService {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        String name="gtlx";
        String password=passwordEncoder.encode("123456");
        String role="admin";

        List<SimpleGrantedAuthority> list=new ArrayList<>();
        list.add(new SimpleGrantedAuthority(role));

        return new User(name,password,list);
    }
}

*********************

config 层

WebSecurityConfig:web安全配置

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    @Bean
    public BCryptPasswordEncoder initPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/**").permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("gtlx")
                .password(passwordEncoder.encode("123456"))
                .authorities("admin");
    }
}

Oauth2ServerConfiguration:认证服务器配置

@Configuration
@EnableAuthorizationServer  //使用注解,开启认证服务器
public class OAuth2ServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    @Resource
    private UserService userService;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer authorizationServerEndpointsConfigurer) throws Exception {
        authorizationServerEndpointsConfigurer.authenticationManager(authenticationManager)
                .userDetailsService(userService);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("user")
                .secret(passwordEncoder.encode("123456"))   //需使用passwordEncoder加密
                .authorizedGrantTypes("password","refresh_token")
                .accessTokenValiditySeconds(3000)           //token的超时时间
                .scopes("user");  //客户端认证scope,可任意设置
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients()
                .passwordEncoder(passwordEncoder)
                .tokenKeyAccess("isAuthenticated()")    //获取token
                .checkTokenAccess("isAuthenticated()"); //验证token
    }
}

*****************************

资源服务器:resource-server

*********************

配置文件

spring:
  application:
    name: resource-server

security:
  oauth2:
    client:
      client-id: user
      client-secret: 123456
    resource:
      id: user
      token-info-uri: http://localhost:8081/oauth/check_token     #向认证服务器验证token的url地址

server:
  port: 8082

*********************

config 层

ResourceServerConfig:资源服务器配置

@Configuration
@EnableResourceServer    //使用注解,开启资源服务器
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/hello").hasAuthority("admin")
                .antMatchers("/hello2").hasAuthority("user");
    }
}

*********************

controller 层

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        return "hello world";
    }

    @RequestMapping("/hello2")
    public String hello2(){
        return "hello 瓜田李下";
    }
}

*****************************

使用测试

*********************

获取token操作

查询参数:grant_type=password&username=gtlx&password=123456

header: key:Authorization,value:Basic dXNlcjoxMjM0NTY=

      

      

*********************

更新token操作

查询参数:grant_type=refresh_token&refresh_token=7f33982d-7acd-4f3a-b151-3cbf1b2fe542

header:key:Authorization,value:Basic dXNlcjoxMjM0NTY=

      

      

*********************

获取resource server数据

header:key:Authorization,value:bearer dd32ff93-8e9a-4ef0-b836-c46dbf1d1364

      

      

发布了331 篇原创文章 · 获赞 92 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43931625/article/details/104130279