例子8--spring-boot-starter-oauth2最新版--普通token的测试--(2)

1、创建config包,后在下面添加3个配置类

(1)

(2)

2、AuthorizationServerConfig的内容

ppackage com.xachen.oauth2jwtcenter.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;


/**
 * @author anxi
 * @version 2020/9/20 19:11
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    public PasswordEncoder passwordEncoder;
//    @Autowired
//    public UserDetailsService userDetailsService;

    @Autowired
    public UserServiceImpl userDetailsService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        //TODO token持久化
        //配置授权服务处理策略
        endpoints.authenticationManager(authenticationManager).userDetailsService(userDetailsService);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //TODO 客户端持久化
        //配置网关服务的用户名密码,仅网关服务可作为客户端可访问oauth服务
        clients.inMemory()
                .withClient("gateway-client").secret(passwordEncoder.encode("123456"))
                .authorizedGrantTypes("refresh_token", "authorization_code", "password")
                .accessTokenValiditySeconds(24 * 3600)
                .scopes("all");
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //允许客户端发送表单来进行权限认证来获取令牌
        security.allowFormAuthenticationForClients()
                //只允许认证的客户端,比如网关服务才可以获取和校验token
                .checkTokenAccess("isAuthenticated()")
                .tokenKeyAccess("isAuthenticated()");
        security.addTokenEndpointAuthenticationFilter(new CorsFilter(corsConfigurationSource()));
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "HEAD", "DELETE", "OPTION"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.addExposedHeader("Authorization");
        configuration.addExposedHeader("Content-disposition");//文件下载消息头
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}

(2)UserServiceImpl的内容

package com.xachen.oauth2jwtcenter.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author anxi
 * @version 2020/9/20 13:21
 */
@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //TODO 用户持久化
        if ("admin".equals(username)) {
            String role = "ROLE_ADMIN";
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority(role));
            String password = passwordEncoder.encode("123456");
            return new User(username, password, authorities);
        }
        throw new UsernameNotFoundException("no user");
    }
}

(3)WebSecurityConfig的内容

package com.xachen.oauth2jwtcenter.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author anxi
 * @version 2020/9/20 19:26
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        //默认的认证操作
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        //加密器
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //允许匿名访问所有接口 主要是 oauth 接口
        http.authorizeRequests().antMatchers("/**").permitAll()
                //以下陈添加  20210309
                .anyRequest().authenticated()
                .and()
                .cors()
                .and()
                .csrf().disable();
    }
}

3、测试方法

(1)base64的在线转换地址如下

https://base64.us/

(2)postman测试如下:

http://localhost:9000/oauth/token?grant_type=password&username=admin&password=123456&scope=all

头中

Authorization
Basic Z2F0ZXdheS1jbGllbnQ6MTIzNDU2

 

 

 测试结果如下

在Spring Boot中,使用`spring-boot-starter-oauth2-client`配置`SecurityFilterChain`可以实现OAuth2客户端的认证和授权功能。下面是配置`SecurityFilterChain`的步骤: 1. 首先,在`application.properties`或`application.yml`文件中配置OAuth2客户端的相关属性,例如: ``` spring.security.oauth2.client.registration.<client-id>.client-id=<client-id> spring.security.oauth2.client.registration.<client-id>.client-secret=<client-secret> spring.security.oauth2.client.registration.<client-id>.redirect-uri=<redirect-uri> spring.security.oauth2.client.registration.<client-id>.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.<client-id>.scope=<scope> spring.security.oauth2.client.provider.<provider-id>.authorization-uri=<authorization-uri> spring.security.oauth2.client.provider.<provider-id>.token-uri=<token-uri> spring.security.oauth2.client.provider.<provider-id>.user-info-uri=<user-info-uri> ``` 2. 创建一个`@Configuration`类,并使用`@EnableWebSecurity`注解启用Web安全功能。 3. 在该配置类中,创建一个实现`SecurityFilterChain`接口的`@Bean`方法,并使用`HttpSecurity`对象进行配置,例如: ```java @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests(authorizeRequests -> authorizeRequests .antMatchers("/login").permitAll() .anyRequest().authenticated() ) .oauth2Login(); return http.build(); } } ``` 4. 在上述配置中,使用`authorizeRequests`方法配置请求的授权规则,例如使用`antMatchers`方法指定某些URL的访问权限,使用`anyRequest`方法指定其他请求的访问权限。 5. 使用`oauth2Login`方法启用OAuth2登录功能,该方法会自动配置OAuth2客户端的登录流程。 6. 最后,将上述配置类添加到Spring Boot应用程序的启动类上,例如: ```java @SpringBootApplication public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值