(7)spring-cloud-starter-oauth2-上

目录

1、pom.xml

2、实体类

3、service-自定义登录逻辑

4、编写安全配置类-WebSecurityConfigurerAdapter

5、编写授权服务配置类-AuthorizationServerConfigurerAdapter

6、编写资源务配置类-ResourceServerConfigurerAdapter

7、测试-获取授权码

8、测试-获取令牌

9、获取资源所有者信息(用户信息)


参考:https://www.cnblogs.com/wuzhenzhao/p/13232530.html

           https://blog.csdn.net/cpongo4/article/details/88895165 

           https://blog.csdn.net/weixin_44516305/article/details/88886839

调试URL:

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


http://localhost:8080/oauth/token?grant_type=authorization_code&client_id=client01&client_secret=secret01&redirect_uri=http://www.baidu.com&scope=all&code=3DXejI


http://localhost:8080/user/getCurrentUser


代码结构:

1、pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>org.example</groupId>
    <artifactId>springsecurity-sso-test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <spring-cloud.version>Greenwich.SR2</spring-cloud.version>
    </properties>


    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--jwt 依赖-->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2、实体类

public class User implements UserDetails {

	private String username;
	private String password;
	private List<GrantedAuthority> authorities;

	public User(String username, String password, List<GrantedAuthority> authorities) {
		this.username = username;
		this.password = password;
		this.authorities = authorities;
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		return authorities;
	}

	@Override
	public String getPassword() {
		return password;
	}

	@Override
	public String getUsername() {
		return username;
	}

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

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

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

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

3、service-自定义登录逻辑

@Service
public class UserService implements UserDetailsService {

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       //自定义登录逻辑
		String password = passwordEncoder.encode("123456");
		return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
	}
}

4、编写安全配置类-WebSecurityConfigurerAdapter

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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


    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/oauth/**", "/login/**", "logout/**")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
//                .loginPage("/login.html")      // 自定义登录的页面
                .permitAll();
    }
}

5、编写授权服务配置类-AuthorizationServerConfigurerAdapter

@Configuration
@EnableAuthorizationServer
public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //配置client-id
                .withClient("admin")
                //配置client-secret
                .secret(passwordEncoder.encode("123456"))
                //配置访问token的有效期
                .accessTokenValiditySeconds(3600)
                //配置刷新Token的有效期
                .refreshTokenValiditySeconds(864000)
                //配置redirect_uri,用于授权成功后跳转
                .redirectUris("http://www.baidu.com")
                //自动授权配置
                .autoApprove(true)
                //配置申请的权限范围g
                .scopes("all")
                //配置grant_type,表示授权类型
                .authorizedGrantTypes("password", "refresh_token", "authorization_code");
    }
}

附:

6、编写资源务配置类-ResourceServerConfigurerAdapter

资源服务器在本例中跟授权服务器放一起,也可分开放,资源是http://localhost:8080/user/getCurrentUser

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
				.anyRequest()
				.authenticated()
				.and()
				.requestMatchers()

				.antMatchers("/user/**");
	}
}
@RestController
@RequestMapping("/user")
public class UserController {
    @GetMapping("/getCurrentUser")
    public Object getCurrentUser(Authentication authentication) {
        return authentication.getPrincipal();//就是user信息
    }

7、测试-获取授权码

http://localhost:8080/oauth/authorize?response_type=code&client_id=client01&redirect_uri=htt
p://www.baidu.com&scope=all

会自动跳至登录页(这是自带的登录页,可以自定义)

 输入用户密码后:

如果自动授权,则:

8、测试-获取令牌

http://localhost:8080/oauth/token?grant_type=authorization_code&client_id=client01&client_secret=secret01&redirect_uri=http://www.baidu.com&scope=all&code=3DXejI

9、获取资源所有者信息(用户信息)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值