前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >spring cloud auth2简单的实战,后续会推出基于spring cloud auth2的SSO实战服务

spring cloud auth2简单的实战,后续会推出基于spring cloud auth2的SSO实战服务

作者头像
gfu
发布2019-11-27 22:48:09
4720
发布2019-11-27 22:48:09
举报
文章被收录于专栏:gfugfu

本文认证基于内存(后续会说基于jdbc),后续会推出基于spring cloud auth2的SSO实战服务。

  1. 本文基于gradle,有用maven的朋友可以移步maven仓库查找对应的jar包
代码语言:javascript
复制
implementation 'org.springframework.cloud:spring-cloud-starter-oauth2'
implementation 'org.springframework.cloud:spring-cloud-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web'
  1. maven仓库地址
代码语言:javascript
复制
[https://mvnrepository.com/](https://mvnrepository.com/)

其实auth2服务还是蛮重要的,作为一个比较大的企业,可能会开发出各种自己公司的产品,这时候就需要单点登录支持,包括业务中台、技术中台的沉淀,这对一个公司来说是非常重要的,一个好公司的良好高效、快速的发展,离不开多年技术的积累,具体的要做什么可以咨询我哦

接下来就是实战了,写了一个比较简单的demo,大家可以在这个基础上进行优化!

1. 继承AuthorizationServerConfigurerAdapter
代码语言:javascript
复制
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

/**
 * AuthorizationServerConfigurerAdapter
 * 
 * @author 719383495@qq.com | 719383495qq@gmail.com | 有问题可以邮箱或者github联系我
 * @date 2019/11/23 9:27
 */
@Configuration
@EnableAuthorizationServer
public class AuthorServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManagerBeans;

    @Autowired
    private TokenStore tokenStore;

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManagerBeans)
                .tokenStore(tokenStore);
    }

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

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("client")
                .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
                .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT", "USER")
                .scopes("all")
                .autoApprove(true)
                .secret(passwordEncoder().encode("secret"));
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.checkTokenAccess("isAuthenticated()");
        security.tokenKeyAccess("isAuthenticated()");
        security.allowFormAuthenticationForClients();
    }
}
  • clients
    • clients直接存放在内存中,可以直接使用client.jdbc()注入datasource,导入数据库脚本,然后oauth2自动回去数据库进行校验,章节长度有限,后续更新SSO的文章会说、会用到!
    • authorizedGrantTypes 认证的类型
    • autoApprove这个是当你访问oauth/authorize的时候,会出现是否通过认证的页面!,这里设置了之后,就会自动通过,不同手动认证通过啦
  • 本文直接用的token,也可以使用jwt,后续的SSO文章会讲到!
2. 继承WebSecurityConfigurerAdapter
代码语言:javascript
复制
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * WebSecurityConfigurerAdapter
 * 
 * @author 719383495@qq.com | 719383495qq@gmail.com | 有问题可以邮箱或者github联系我
 * @date 2019/11/23 9:34
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    PasswordEncoder passwordEncoder;

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

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        UserDetails user = User.builder().username("user").password(passwordEncoder.encode("secret")).roles("USER").build();
        UserDetails userAdmin = User.builder().username("admin").password(passwordEncoder.encode("secret")).roles("ADMIN").build();
        return new InMemoryUserDetailsManager(user, userAdmin);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/customer");
    }
}
  • 这里有一个userDetailsService的bean,这里就是用来验证登录的用户,然后赋予他们的权限。但是你看到这,你自己是不是会思考一个问题,如果用户量很大,这里如果要是这样写,是不是要写疯掉。当然啦,后续的SSO章节会讲到,我们是会从数据库中拉数据进行验证和赋予权限的,这个不用担心0->-0.
3. 继承ResourceServerConfigurerAdapter
代码语言:javascript
复制
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.web.bind.annotation.RestController;

/**
 * ResourceServerConfigurerAdapter
 * 
 * @author 719383495@qq.com | 719383495qq@gmail.com | 有问题可以邮箱或者github联系我
 * @date 2019/11/23 9:37
 */
@EnableResourceServer
@RestController
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
//        http.authorizeRequests().antMatchers("/oauth/token", "/oauth/authorize**", "/customer").permitAll()
//                .anyRequest().authenticated();

        http.requestMatchers().antMatchers("/private")
                .and().authorizeRequests()
                .antMatchers("/private").access("hasRole('USER')")
                .and().requestMatchers().antMatchers("/admin")
                .and().authorizeRequests()
                .antMatchers("/admin").access("hasRole('ADMIN')").anyRequest().authenticated();
    }   
}
  • 这个就是对访问的资源进行控制啦!
4. 写一个controller
代码语言:javascript
复制
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Controller {

    @RequestMapping("/admin")
    public String admin() {
        return "admin access successful";
    }

    @RequestMapping("/private")
    public String user() {
        return "private access successful";
    }

    @RequestMapping("/customer")
    public String customer() {
        return "customer access successful";
    }

}
5. postman使用过程
  • 本次采用的password认证方式,下一篇文章使用的是authorization_code的方式!
  • 使用basic认证
  • post参数调好,见下图,开启服务,就可以发起请求啦
  • 获取到token,和jwt token还是有点区别的,一个长一个短
  • 访问我们写的controller中的uri,你们看看是不是不同的用户登录是不是有些会访问不到呀!
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 接下来就是实战了,写了一个比较简单的demo,大家可以在这个基础上进行优化!
    • 1. 继承AuthorizationServerConfigurerAdapter
      • 2. 继承WebSecurityConfigurerAdapter
        • 3. 继承ResourceServerConfigurerAdapter
          • 4. 写一个controller
            • 5. postman使用过程
            相关产品与服务
            数据库
            云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档