spring boot Security Oauth2.0简单集成

pom文件

<!-- security依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <version>2.3.3.RELEASE</version>
        </dependency>

        <!--web依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </dependency>

用户实体
为了方便操作,给用户赋权限(上篇使用了Security 的 USER对象,这次换个方式耍耍吧)

/**
 * @Title: LoginAppUser
 * @description: 用户信息管理
 * @author: LIUFANG
 * @create: 2020/3/13 12:54
 * @Version: v1.0
 */
@Getter
@Setter
public class LoginAppUser implements UserDetails {

    private Long id;
    private String username;
    private String password;
    private String nickname;
    private String headImgUrl;
    private String phone;
    private Integer sex;
    /**
     * 状态
     */
    private Boolean enabled;
    private String type;
    private String deptId;
    private String deptName;
    private Date createTime;
    private Date updateTime;

    private Set<String> sysRoles;

    private Set<String> permissions;
    /**权限的操作直接放在此处了,简单粗暴,如果你开心,你可以把类做的细化一点*/
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> collection = new HashSet<>();
        /**为什么加ROLE_,看了一下源码,你可以理解为:区分资源和权限的标识符*/
        collection.add(new SimpleGrantedAuthority("ROLE_"+"USER"));
        return collection;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
    @Override
    public String getUsername() {
        /**写死的数据,真实开发查询数据库就OK了*/
        return "user";
    }

UserDetailsService

/**
 * @Title: MyUserDetailsService
 * @description: 用户管理
 * @author: LIUFANG
 * @create: 2020/3/13 9:27
 * @Version: v1.0
 */
@Component
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private PasswordEncoder userPasswordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LoginAppUser loginAppUser = new LoginAppUser();
        loginAppUser.setUsername("user");
        loginAppUser.setPassword(userPasswordEncoder.encode("123456"));
        return loginAppUser;
    }
}

WebSecurityConfig

/**
 * @Title: SecurityConfig
 * @description: 权限配置
 * @author: LIUFANG
 * @create: 2020/3/13 9:12
 * @Version: v1.0
 */
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@Configuration
@Order(2)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailsService userDetailsService;

    /**
     * 一定要将 userDetailsService 设置到 AuthenticationManagerBuilder 中
     * 不然后面校验ClientDetailsService时会找不到UsernamePasswordToken的Provider
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(userPasswordEncoder());
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
       http.csrf().disable();
        http.requestMatchers().antMatchers("/oauth/**","/login/**","/logout/**")
            .and()
            .authorizeRequests()
            .antMatchers("/oauth/**").authenticated()
            .and()
            .formLogin().permitAll(); //新增login form支持用户登录及授权
    }

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


    /**
     * 覆盖WebSecurityConfigurerAdapter类(本类集成的爸爸)authenticationManagerBean的方法,最终要的一点,重写的时候,直接使用super就OK,这波操作给6分
     * 注意的是,这个bean不重写,在OauthAuthorizationServerConfig是无法获取的,这个是个小坑
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception{
        return super.authenticationManager();
    }

Oauth 配置类

/**
 * @Title: OauthAuthorizationServerConfig
 * @description: Oauth2.0配置
 * @author: LIUFANG
 * @create: 2020/3/13 10:22
 * @Version: v1.0
 */
@Configuration
@EnableAuthorizationServer
public class OauthAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    /**这个地方需要注意一下,这个bean必须自行创建出来,参照WebSecurityConfig类*/
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private MyUserDetailsService userDetailsService;

    /**
     * 配置访问端点和令牌服务
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        /**注意这个allowFormAuthenticationForClients,开启表单验证*/
        security
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()")
                .allowFormAuthenticationForClients();
    }

    /**
     * 用来配置客户端详情服务
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        /**client信息,可以存储数据库,可以redis,也可以存储内存,看你心情*/
        clients.inMemory()
                .withClient("system")
                .secret(passwordEncoder.encode("123456"))
                .authorizedGrantTypes("authorization_code", "refresh_token", "password")
                .scopes("app");
    }

    /**
     * 配置token
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        /**直接存储内存*/
        endpoints
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
                .authenticationManager(authenticationManager)
                .tokenStore(new InMemoryTokenStore())
                .userDetailsService(userDetailsService);

    }
}

ResourceServerConfig资源服务器
这个类的作用是为Oauth请求服务,必须配置

/**
 * @Title: ResourceServerConfig
 * @description: 资源服务配置
 * @author: LIUFANG
 * @create: 2020/3/13 13:54
 * @Version: v1.0
 */
@Configuration
@EnableResourceServer
@Order(6)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/user/**").hasAnyRole("ADMIN","USER")
                .antMatchers("/test").authenticated()
                .anyRequest().authenticated();
    }
}

controller调用

/**
 * @Title: MyController
 * @description: 测试Controller
 * @author: LIUFANG
 * @create: 2020/3/13 10:56
 * @Version: v1.0
 */
@RestController
public class MyController {
    @GetMapping(value = "/test")
    public Object test(){
        return "test";
    }

    @GetMapping(value = "/user")
    @PreAuthorize("hasAnyRole('ROLE_USER')")
    public Object user(){
        return "user";
    }

    @GetMapping(value = "/user/a")
    public Object user2(){
        return "user";
    }

    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    @GetMapping(value = "/admin")
    public Object admin(){
        return "admin";
    }

    @GetMapping(value = "/admin/b")
    public Object admin2(){
        return "admin";
    }
}

http请求验证

/**http 请求 URL*/
GET http://localhost:8888/user/a
/**header中需要添加消息头:*/
Authorization: Bearer 775d36ad-d224-463b-8632-9cc4e9518d41
image.png

获取code

http://localhost:8080/oauth/authorize?client_id=system&response_type=code&scope=app&redirect_uri=http://www.baidu.com

使用code 获取access_token

curl -X POST -d "grant_type=authorization_code&code=Ii2ZNI&client_id=system&client_secret=123456&redirect_uri=http://www.baidu.com" http://localhost:8080/oauth/token
出参:

{
 "access_token": "df23f20a-59ee-4288-9582-040718846ff3",
 "token_type": "bearer",
 "refresh_token": "63b0ad83-6168-4b62-abeb-ab64d1154abd",
 "expires_in": 43199,
 "scope": "app"
}

参考:
https://blog.csdn.net/liu__hui2008ooo/article/details/104904137

https://blog.csdn.net/qq_27828675/article/details/82466599

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容