spring security Oauth2入门示例

36 篇文章 0 订阅
16 篇文章 0 订阅

spring security Oauth2

依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-oauth2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Hoxton.SR8</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

配置

// spring security 认证类
@Service
public class UserService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        String pwd = passwordEncoder.encode("123456");
        return new User(username,pwd,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin,sysadmin"));
    }
}

// 用于测试的资源
@RestController
@RequestMapping("/user")
public class UserController {

    @RequestMapping("getCurrentUser")
    public Object getCurrentUser(Authentication authentication){
        return authentication.getPrincipal();
    }
}
// spring security 权限认证配置
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/oauth/**","/login/**","/logout/**")
                .permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().permitAll()
                .and()
                .csrf()
                .disable()
        ;
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
// 认证服务器配置
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("client")
                .secret(passwordEncoder.encode("878412"))
                .redirectUris("http://www.baidu.com")
                .scopes("all")
                .authorizedGrantTypes("authorization_code");
    }
}
// 资源服务器配置
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("client")
                .secret(passwordEncoder.encode("878412"))
            // 用于接收授权码,一般在此页面中再依据授权码去获取授权令牌。
                .redirectUris("http://www.baidu.com")
                .scopes("all")
                .authorizedGrantTypes("authorization_code");
    }
}

启动类

​ 普通的springboot启动类。

使用测试

  1. 获取授权码

    http://localhost:8080/oauth/authorize?response_type=code&client_id=client&redirect_uri=http://localhost:8081/test&scope=all

    参数说明:

    ​ response_type: code --授权码

    ​ client_id: client – AuthorizationServerConfig配置文件中配置的withClient

    ​ redirect_uri:http://localhost:8081/test – AuthorizationServerConfig配置文件中配置的redirectUris。

    ​ scope:all – 授权类型 ,AuthorizationServerConfig配置文件中配置的scopes。

    请求上面的地址后先会跳转到登录页面,使用UserService配置的账号密码登录后会跳转到授权页面,授权后才会跳转到百度,并附带授权码(本例中没有校验账号,只校验密码为123456即可,所以账号可以随意输入,密码为123456)

  2. 用获取到的授权码再去请求授权令牌(使用postman来测试)

    地址:http://localhost:8080/oauth/token

    认证方式:Basic Auth ,账号、密码:AuthorizationServerConfig配置文件中配置的withClient、secret的值

    参数:

    参数名
    grant_typeauthorization_code
    client_idclient
    redirect_urihttp://localhost:8081/test
    scopeall
    code上面获取到的授权吗

在这里插入图片描述

  1. 依据授权令牌请求资源

    地址:http://localhost:8080/user/getCurrentUser

    授权方式:bearer token

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蜗牛_snail

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值