Oauth2

从头开始spring security oauth 2.0 (三

2018-06-27  本文已影响135人  GoddyWu

一定要读下这个 https://github.com/jeansfish/RFC6749.zh-cn !!!然而本节没用到这个。

首先,明确下数据库表:

@Data
@Entity
@Table(name = "oauth_user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    /** 用户名 */
    @Column(nullable = false, unique = true)
    private String username;

    /** 密码 */
    private String password;

    /** 是否可用 */
    private Boolean enabled;

    /** 是否被锁 */
    private Boolean noLocked;

    /** 权限 */
    private String authorities;
}
@Data
@Entity
@Table(name = "oauth_client")
public class Client {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "client_id", unique = true)
    private String clientId;

    private String resourceIds;

    private String clientSecret;

    private Boolean secretRequire;

    private String scope;

    private Boolean scopeRequire;

    private String authorizedGrantTypes;

    private String authorities;

    private Integer accessTokenValidity;

    private Integer refreshTokenValidity;
}

重点来了,authorities存放的是authority,如果authority存放的是以ROLE_开头的,那么它就是该user/client的role,一定要明确这点。

然后,我们通过继承ResourceServerConfigurerAdapter来同一通过路由管理权限,示例如下:

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources
                .resourceId(Constant.RESOURCE_ID_NORMAL_APP)
                .stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                // Since we want the protected resources to be accessible in the UI as well we need
                // session creation to be allowed (it's disabled by default in 2.0.6)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and()
                .requestMatchers().anyRequest()
                .and()
                .authorizeRequests()
//                    .antMatchers("/product/**").access("#oauth2.hasScope('select') and hasRole('ROLE_USER')")
                //配置order访问控制,必须认证过后才可以访问
                .antMatchers("/user/**").access("hasAuthority('READ') and hasRole('ADMIN')")
                .antMatchers("/client/**").hasRole("MASTER")
//                .antMatchers("/client/{clientId}").hasRole("MASTER")
                .antMatchers("/test/**").permitAll()
                .antMatchers("/order/**").authenticated();
    }
}

其他不做解释,分析下这几个antMatchers即拦截器。
第一个,要求有'READ'的authority和'ADMIN'的role(当然数据库存储为“ROLE_ADMIN”)
第二个,需要有'MASTER'的role。
第三个,允许所有。
第四个,登陆了就行。

上一篇下一篇

猜你喜欢

热点阅读