Sercurity + Auth2框架实现认证授权

SpringSecurity 是Spring家族的一员,是Spring家族提供的安全框架,提供认证和授权功能,最主要的是它提供了简单的使用方式,同时又有很高的灵活性,简单,灵活,强大。

主要的主要的几个配置类

自定义Security的策略

AuthorizationServerConfigurerAdapter

例子如下:

@Configuration

@EnableAuthorizationServer

public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Override

    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        endpoints

                .authenticationManager(authenticationManager)

                .tokenGranter(new CompositeTokenGranter(getTokenGranters(endpoints)))

                .userDetailsService(userDetailsService)

                .tokenStore(tokenStore());

}

@Override

    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        //存放到db

        clients.jdbc(dataSource);

//        存放到内存

        clients.inMemory()

                .withClient("webapp")

                .secret(pass)

                .scopes("server")

                .authorizedGrantTypes("password", "authorization_code", "refresh_token")

                .accessTokenValiditySeconds(24 * 60 * 60) //token有效期

                .refreshTokenValiditySeconds(24 * 60 * 60)

                .and().withClient("app")

                .secret(pass)

                .scopes("app")

                .authorizedGrantTypes("authorization_code", "refresh_token")

                .redirectUris("https://www.baidu.com/");

    }

/**

    * 填充认证方式

    * @param endpoints endpoints

    * @return list

    */

    private List<TokenGranter> getTokenGranters(AuthorizationServerEndpointsConfigurer endpoints) {

        AuthorizationServerTokenServices tokenServices = endpoints.getTokenServices();

        ClientDetailsService clientDetailsService = endpoints.getClientDetailsService();

        OAuth2RequestFactory oAuth2RequestFactory = endpoints.getOAuth2RequestFactory();

        AuthorizationCodeServices authorizationCodeServices = endpoints.getAuthorizationCodeServices();

        return new ArrayList<>(Arrays.asList(

                new RefreshTokenGranter(tokenServices, clientDetailsService, oAuth2RequestFactory),

                new AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, clientDetailsService,

                        oAuth2RequestFactory),

                new ResourceOwnerPasswordTokenGranter(authenticationManager, endpoints.getTokenServices(),

                        clientDetailsService, oAuth2RequestFactory),

                new MyAbstractTokenGranter(authenticationManager, tokenServices, clientDetailsService,

                        oAuth2RequestFactory)));

    }

}


默认情况下spring security oauth 的http配置。

ResourceServerConfigurerAdapter:

例子如下

@Configuration

@EnableResourceServer

public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override

    public void configure(HttpSecurity http) throws Exception {

        http

                .csrf().disable()

                .exceptionHandling()

                .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))

                .and()

                .authorizeRequests()

                .antMatchers("/index/getUser").permitAll()

                .antMatchers("/user/getUserPassword").permitAll()

                .anyRequest().authenticated()

                .and()

                .httpBasic();

    }

}

WebSecurityConfigurerAdapter 类是个适配器, 需要配置的时候需要我们自己写个配置类去继承,根据自己的需求去进行配置即可WebSecurityConfigurerAdapter的配置拦截要优先于ResourceServerConfigurerAdapter,优先级高的http配置是可以覆盖优先级低的配置的。

WebSecurityConfigurerAdapter

例子如下:

@Configuration

@EnableWebSecurity

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**

    * 自定义实现用户信息获取

    *

    * @return

    */

    @Bean

    @Override

    public UserDetailsService userDetailsService() {

        return new MyUserDetailsServiceImpl();

    }

    /**

    * @param auth

    * @throws Exception

    */

    @Override

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService())

                .passwordEncoder(passwordEncoder());

    }

    /**

    * @param http

    * @throws Exception

    */

    @Override

    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable()

                .authorizeRequests().anyRequest().authenticated()

                .and()

                .httpBasic();

    }

    /**

    * 不定义没有password grant_type

    */

    @Override

    @Bean

    public AuthenticationManager authenticationManagerBean() throws Exception {

        return super.authenticationManagerBean();

    }

    /**

    * 密码解析器

    * @return PasswordEncoder

    */

    @Bean

    public PasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();

    }

}

继承了抽象类 AbstractTokenGranter

AbstractTokenGranter

public class MyAbstractTokenGranter extends AbstractTokenGranter {

    @Autowired

    private UserInfo userInfo;

    @Autowired

    private RedisUtil redisUtil;

    private static final String GRANT_TYPE = "sms_cod";

    private final AuthenticationManager authenticationManager;

    public MyAbstractTokenGranter(AuthenticationManager authenticationManager,

                                  AuthorizationServerTokenServices tokenServices,

                                  ClientDetailsService clientDetailsService,

                                  OAuth2RequestFactory requestFactory) {

        this(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);

    }

    protected MyAbstractTokenGranter(AuthenticationManager authenticationManager,

                                    AuthorizationServerTokenServices tokenServices,

                                    ClientDetailsService clientDetailsService,

                                    OAuth2RequestFactory requestFactory, String grantType) {

        super(tokenServices, clientDetailsService, requestFactory, grantType);

        this.authenticationManager = authenticationManager;

    }

    /**

    * 我们拿到的 token 终会过期的, 对应于刷新 token模式的 RefreshTokenGranter 则负责获取新的 OAuth2AccessToken。

    *

    * @param client

    * @param tokenRequest

    * @return

    */

    @Override

    protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) {

        // 传入的参数需要有 refresh_token (DefaultOAuth2AccessToken 中有 refreshToken 字段)

        String refreshToken = tokenRequest.getRequestParameters().get("refresh_token");

        // 调用 tokenService 的刷新方法得到新的 OAuth2AccessToken

        return getTokenServices().refreshAccessToken(refreshToken, tokenRequest);

    }

    /**

    * 用户拦截

    *

    * @param client      client

    * @param tokenRequest 请求的令牌

    * @return

    */

    @Override

    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {

        Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());

        String username = parameters.get("username");

        String password = parameters.get("password");

        String mobile = parameters.get("mobile");

        //客户端提交的验证码

        String smscode = parameters.get("sms_cod");

        String type = parameters.get("type");

        parameters.remove("password");

        //验证用户状态(是否警用等)

//        UserInfo userInfo = new UserInfo();

//        userInfo.setMobile(mobile);

        // 验证验证码

        //获取服务中保存的用户验证码

        String smsCheckCode = (String) redisUtil.get(userInfo.getMobile());

        if (StringUtils.isBlank(smsCheckCode)) {

            throw new InvalidGrantException("用户没有发送验证码");

        }

        if (!smscode.equals(smsCheckCode)) {

            throw new InvalidGrantException("验证码不正确");

        } else {

            //验证通过后从缓存中移除验证码

            redisUtil.setRemove(userInfo.getMobile(), smsCheckCode);

        }

        if (username.isEmpty()) {

            throw new InvalidGrantException("用户不存在");

        }

        Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password);

        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);

        try {

            userAuth = authenticationManager.authenticate(userAuth);

        } catch (AccountStatusException ase) {

            //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)

            throw new InvalidGrantException(ase.getMessage());

        } catch (BadCredentialsException e) {

            // If the username/password are wrong the spec says we should send 400/invalid grant

            throw new InvalidGrantException(e.getMessage());

        }

        if (userAuth == null || !userAuth.isAuthenticated()) {

            throw new InvalidGrantException("Could not authenticate user: " + username);

        }

        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);

        return new OAuth2Authentication(storedOAuth2Request, userAuth);

    }

核心依赖配置配置如下:

<dependency>

            <groupId>org.springframework.security.oauth</groupId>

            <artifactId>spring-security-oauth2</artifactId>

            <version>${oauth2.version}</version>

        </dependency>

        <dependency>

            <groupId>org.springframework.cloud</groupId>

            <artifactId>spring-cloud-starter-security</artifactId>

            <exclusions>

                <!--旧版本 redis操作有问题-->

                <exclusion>

                    <artifactId>spring-security-oauth2</artifactId>

                    <groupId>org.springframework.security.oauth</groupId>

                </exclusion>

            </exclusions>

使用SpringSrcurity+Anut2根据token实现用户密码登录

service层

/**

    * 根据用户名查询

    * @param userName 用户名

    * @return 返回的路径

    */

    UserInfo getUserInfoByName(@Param("userName") String userName);

Service层

@Service

public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Autowired

    public PasswordEncoder passwordEncoder;

    @Resource

    private UserInfoService userInfoService;

    @Resource

    private UserInfoMapper userInfoMapper;

    @Override

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserInfo userInfo = userInfoService.getUserInfoByName(username);

        if (userInfo == null){

            throw new UsernameNotFoundException(username);

        }

        return userInfo;

    }

Controlleer层

@RestController

@RequestMapping("/")

public class IndexController {

    /**

    * user

    * @param user user

    * @return Principal

    */

    @GetMapping(value = "/user")

    public Principal user(Principal user) {

        return user;

    }

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