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

2019-11-23  本文已影响0人  爱吃苹果的西瓜

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

  1. 本文基于gradle,有用maven的朋友可以移步maven仓库查找对应的jar包
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仓库地址
[https://mvnrepository.com/](https://mvnrepository.com/)
  1. 推荐使用阿里云的仓库地址
    maven { url = 'http://maven.aliyun.com/nexus/content/groups/public/' }

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

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


1. 继承AuthorizationServerConfigurerAdapter

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();
    }
}

2. 继承WebSecurityConfigurerAdapter

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");
    }
}

3. 继承ResourceServerConfigurerAdapter

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

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使用过程

上一篇 下一篇

猜你喜欢

热点阅读