栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

孤尽训练营打卡日记day22--OAuth2实战

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

孤尽训练营打卡日记day22--OAuth2实战

前言

        在前面的笔记分享中,我们知道了OAuth 2是什么,他是一个第三方登录的授权协议。为什么要使用 OAuth 2,因为现在是分布式架构,对客户来说,是一个系统,但是后台实现是多个微服务,客户一次登录,应该要能访问到不同的微服务。今天我们接着学习 OAuth2 的实战。

工程结构;

        授权服务器:颁发和验证令牌

        提供需要令牌才能访问的服务

依赖


    org.springframework.cloud
    spring-cloud-starter-oauth2


    org.springframework.cloud
    spring-cloud-starter-security

授权服务器配置

oauth2 配置类继承 

AuthorizationServerConfigurerAdapter

开启授权服务器

@EnableAuthorizationServer

客户端信息配置

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()
                .withClient(CLIENT_ID)
                .secret(SECRET_CHAR_SEQUENCE)
                .autoApprove(false)
                .redirectUris("http://127.0.0.1:8084/cms/login") //重定向uri
                .scopes(ALL)
                .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
                .authorizedGrantTypes(AUTHORIZATION_CODE, IMPLICIT, GRANT_TYPE_PASSWORD, CLIENT_CREDENTIALS);
    }

存储令牌

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager).tokenStore(memoryTokenStore());
    }
    @Bean
    public TokenStore memoryTokenStore() {
        return new InMemoryTokenStore();
    }

oauth2端点权限

    
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                //  开启/oauth/check_token验证端口认证权限访问,checkTokenAccess("isAuthenticated()")设置授权访问
                .checkTokenAccess("permitAll()")
                //允许表单认证
                .allowFormAuthenticationForClients();
    }

SecurityConfig配置类 继承

WebSecurityConfigurerAdapter

开启Spring Security 

@EnableWebSecurity

设置用户角色数据内存存储

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {    //auth.inMemoryAuthentication()
        auth.inMemoryAuthentication()
                .withUser("lxs")
                .password("{noop}123") //使用springsecurity5,需要加上{noop}指定使用NoOpPasswordEncoder给DelegatingPasswordEncoder去校验密码
                .roles("admin");
    }

放行静态资源

    @Override
    public void configure(WebSecurity web) throws Exception {
        //解决静态资源被拦截的问题
//        web.ignoring().antMatchers("/asserts/**");
    }

授权资源全局配置

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .formLogin().permitAll()
                .and().logout().logoutUrl("/logout").logoutSuccessUrl("/")
                .and().authorizeRequests().antMatchers("/oauth/**", "/login/**", "/logout/**", "/api/**").permitAll()
                .anyRequest().authenticated()
                // 关闭跨域保护;
                .and().csrf().disable();
    }

资源服务器配置

Oauth2配置类继承

ResourceServerConfigurerAdapter
@Configuration
@EnableResourceServer
public class Oauth2ResourceServerConfiguration extends
    ResourceServerConfigurerAdapter {

  private static final String CHECK_TOKEN_URL = "http://localhost:8888/oauth/check_token";

  @Override
  public void configure(ResourceServerSecurityConfigurer resources) {
    RemoteTokenServices tokenService = new RemoteTokenServices();
    // 授权服务器令牌校验地址
    tokenService.setCheckTokenEndpointUrl(CHECK_TOKEN_URL);
    // 客户端信息
    tokenService.setClientId("cms");
    tokenService.setClientSecret("secret");

    resources.tokenServices(tokenService);
  }

}

Security配置类继承

WebSecurityConfigurerAdapter
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    // 授权拦截路径
    http.authorizeRequests().antMatchers("/**").authenticated();
    // 禁用CSRF,关闭跨域保护
    http.csrf().disable();
  }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/531057.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号