oauth2整合security

什么是oauth2

OAuth 2.0 是一个授权协议,它允许软件应用代表(而不是充当)资源拥有者去访问资源拥有者的资源。应用向资源拥有者请求授权,然后取得令牌(token),并用它来访问资源,并且资源拥有者不用向应用提供用户名和密码等敏感数据。
当前有一个开放接口 该接口
会被非常多的商户端来调用
管理商户端
开放接口平台设计

第三方支付接口 或者 第三方知名平台接口
微信 支付宝 等。

流程

1.申请一个appid 和 秘钥
Appid=QQ账户—终生无法变化
Apppwd
===QQ密码
2.appid 和密码 获取token
3.需要使用该token调用接口
4.Token 临时且唯一 2个小时 8个小时
Token 失效----刷新token

Oauth角色划分

1、Resource Server:被授权访问的资源
2、Authotization Server:OAUTH2认证授权中心
3、Resource Owner: 用户
4、Client:使用API的合作伙伴

整合代码

1. Authotization Server:OAUTH2认证授权中心模块

  <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-freemarkerartifactId>
        dependency>

        spring-boot 整合security -->
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-securityartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.security.oauthgroupId>
            <artifactId>spring-security-oauth2artifactId>
            <version>2.2.1.RELEASEversion>
        dependency>


        <dependency>
            <groupId>io.jsonwebtokengroupId>
            <artifactId>jjwtartifactId>
            <version>0.6.0version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.62version>
        dependency>
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-lang3artifactId>
        dependency>
    dependencies>

security认证 里面认证用户名和密码

@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
     
    @Bean
    public PasswordEncoder passwordEncoder() {
     
        return new BCryptPasswordEncoder();
    }

    /**
     * 需要填写 认证账户  mayikt
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
     
        auth.inMemoryAuthentication()
                .withUser("mayikt")
                .password(passwordEncoder().encode("mayikt"))
                .authorities("/*");

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
     
        http.authorizeRequests()
                .anyRequest().authenticated() //所有请求都需要通过认证
                .and()
                .httpBasic() //Basic登录
                .and()
                .csrf().disable(); //关跨域保护
    }
}

认证授权Server端 需提供appId,密钥,回调地址 ,资源Id

/**
 * 认证授权Server端
 */
@Component
@EnableAuthorizationServer
public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
     
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
     
        //允许表单提交
        security.allowFormAuthenticationForClients()
                .checkTokenAccess("permitAll()");
    }

    /**
     * appid mayikt secret= 123456
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
     
        clients.inMemory()
                // appid 表里取 这里写死
                .withClient("appId")
                // 密钥  表里取 这里写死
                .secret(passwordEncoder.encode("123456"))
                // 授权码
                .authorizedGrantTypes("authorization_code")
                // 作用域
                .scopes("all")
                // 资源的id  表里取 这里写死
                .resourceIds("mayikt_resource")
                // 回调地址  表里取 这里写死
                .redirectUris("http://www.mayikt.com/callback");


    }
}

获取access_token步骤

1. 获取授权码
http://localhost:8080/oauth/authorize?client_id=appId&response_type=code
通过访问这个地址获取授权码 ,client_id值为
oauth2整合security_第1张图片

访问接口填写账户和密码
oauth2整合security_第2张图片
访问成功后通过回调地址获取授权码
oauth2整合security_第3张图片
2.根据授权码获取accessToken
http://localhost:8080/oauth/token?code=6s9qUj&grant_type=authorization_code&redirect_uri=http://www.mayikt.com/callback&scope=all

redirect_uri:回调地址
code:授权码

通过postman post请求 填写appid和密钥就可以获取token

oauth2整合security_第4张图片

2. Resource Server:被授权访问的资源

 <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-freemarkerartifactId>
        dependency>

        spring-boot 整合security -->
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-securityartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.security.oauthgroupId>
            <artifactId>spring-security-oauth2artifactId>
            <version>2.2.1.RELEASEversion>
        dependency>


        <dependency>
            <groupId>io.jsonwebtokengroupId>
            <artifactId>jjwtartifactId>
            <version>0.6.0version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.62version>
        dependency>
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-lang3artifactId>
        dependency>
    dependencies>

资源Server端

/**
 * 资源Server端
 */
@Configuration
@EnableResourceServer
public class ResourceConfig extends ResourceServerConfigurerAdapter {
     

     //appID
    private String mayiktAppId ="appId";
     //密钥
    private String mayiktAppSecret ="123456";

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

    @Primary
    @Bean
    public RemoteTokenServices remoteTokenServices() {
     
        final RemoteTokenServices tokenServices = new RemoteTokenServices();
        //设置授权服务器check_token端点完整地址
        tokenServices.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");
        //设置客户端id与secret,注意:client_secret值不能使用passwordEncoder加密!
        tokenServices.setClientId(mayiktAppId);
        tokenServices.setClientSecret(mayiktAppSecret);
        return tokenServices;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
     
        //设置创建session策略
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
        //@formatter:off
        //所有请求必须授权
        http.authorizeRequests().anyRequest().authenticated();
        //@formatter:on
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
     
        resources.resourceId("mayikt_resource").stateless(true);
    }
}
@RestController
public class MemberService {
     
    @GetMapping("/getMember")
    public String getMember() {
     
        return "我是会员服务接口";
    }
}

带上token访问成功
oauth2整合security_第5张图片

你可能感兴趣的:(java,安全,spring,boot)