Spring Security oauth2密码模式和主要组成的配置文件流程图

 1、构造了流层图,帮助理解oauth2,(图片自己编辑的为啥涉嫌违规,没有广告,没有很多外链,篇幅也不短,算了,本来就是笔记,小破站~~)

1.SecurityConfig

package com.example.demo.security.config;

import com.example.demo.security.service.UserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;

@EnableWebSecurity
@Order(2)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailService userDetailService;

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

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
                .antMatchers("/oauth/**")
                .and()
                .authorizeRequests()
                .antMatchers("/oauth/**").authenticated()
                .and()
                .csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder());
    }

}

 2.ResourceServerConfig

package com.example.demo.security.config;

import org.springframework.context.annotation.Configuration;
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;

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .requestMatchers().antMatchers("/**")
                .and()
                .authorizeRequests()
                .antMatchers("/**").authenticated();
    }

}

 3.AuthorizationServerConfig

package com.example.demo.security.config;

import com.example.demo.security.service.UserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
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.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {


    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
    @Autowired
    private UserDetailService userDetailService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("auth")
                .secret(passwordEncoder.encode("123456"))
                .authorizedGrantTypes("password", "refresh_token")
                .scopes("all");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.tokenStore(tokenStore())
                .userDetailsService(userDetailService)
                .authenticationManager(authenticationManager)
                .tokenServices(defaultTokenServices());
    }

    /**
     * 认证服务器生成的令牌将被存储到Redis中
     * @return
     */
    @Bean
    public TokenStore tokenStore() {
        return new RedisTokenStore(redisConnectionFactory);
    }

    @Primary
    @Bean
    public DefaultTokenServices defaultTokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(tokenStore());
        // 开启刷新令牌的支持
        tokenServices.setSupportRefreshToken(true);
        // 令牌有效时间为60 * 60 * 24
        tokenServices.setAccessTokenValiditySeconds(60 * 60 * 24);
        // 刷新令牌有效时间为60 * 60 * 24 * 7秒
        tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 7);
        return tokenServices;
    }
}


参考链接

Spring Security OAuth2--密码模式 实战_爱撸铁的程序猿的博客-CSDN博客_oauth2密码模式用户登录

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要自定义Spring Security OAuth2密码模式的登录路径,你可以使用以下步骤: 1. 创建自定义登录页面和控制器,例如/login/custom。 2. 在Spring Security配置类中,使用formLogin()方法启用表单登录,并使用loginPage()方法指定登录页面的路径和permitAll()方法允许所有用户访问登录页面。 ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login/custom") .permitAll() .and() .oauth2Login() .and() .oauth2Client(); } } ``` 3. 在控制器中,编写处理登录请求的方法,并使用AuthenticationManager.authenticate()方法进行身份验证。如果身份验证成功,重定向到请求的资源,否则返回登录页面。 ``` @Controller public class LoginController { @Autowired private AuthenticationManager authenticationManager; @GetMapping("/login/custom") public String showLoginForm() { return "login"; } @PostMapping("/login/custom") public String submitLoginForm(@RequestParam String username, @RequestParam String password, HttpServletRequest request, HttpServletResponse response) { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password); try { Authentication authentication = authenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(authentication); return "redirect:" + request.getParameter("redirect_uri"); } catch (AuthenticationException e) { return "login"; } } } ``` 4. 在OAuth2客户端配置中,使用loginPage()方法指定登录页面的路径。 ``` @Configuration @EnableOAuth2Client public class OAuth2ClientConfig { @Value("${security.oauth2.client.client-id}") private String clientId; @Value("${security.oauth2.client.client-secret}") private String clientSecret; @Value("${security.oauth2.client.access-token-uri}") private String accessTokenUri; @Value("${security.oauth2.client.user-authorization-uri}") private String userAuthorizationUri; @Value("${security.oauth2.client.redirect-uri}") private String redirectUri; @Value("${security.oauth2.client.scope}") private String scope; @Bean public OAuth2ProtectedResourceDetails oauth2ProtectedResourceDetails() { ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails(); details.setClientId(clientId); details.setClientSecret(clientSecret); details.setAccessTokenUri(accessTokenUri); details.setScope(Arrays.asList(scope.split(","))); return details; } @Bean public OAuth2RestTemplate oauth2RestTemplate() { OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(oauth2ProtectedResourceDetails()); restTemplate.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter())); return restTemplate; } @Bean public OAuth2ClientContext oauth2ClientContext() { return new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()); } @Bean public AuthorizationCodeResourceDetails authorizationCodeResourceDetails() { AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails(); details.setClientId(clientId); details.setClientSecret(clientSecret); details.setAccessTokenUri(accessTokenUri); details.setUserAuthorizationUri(userAuthorizationUri); details.setScope(Arrays.asList(scope.split(","))); details.setUseCurrentUri(false); details.setPreEstablishedRedirectUri(redirectUri); details.setAuthenticationScheme(AuthenticationScheme.query); return details; } @Bean public OAuth2RestOperations oauth2RestOperations() { return new OAuth2RestTemplate(authorizationCodeResourceDetails(), oauth2ClientContext()); } @Bean public OAuth2ClientAuthenticationProcessingFilter oauth2ClientAuthenticationProcessingFilter() { OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter("/login/custom"); OAuth2RestTemplate restTemplate = oauth2RestTemplate(); restTemplate.setAccessTokenProvider(new AuthorizationCodeAccessTokenProvider()); filter.setRestTemplate(restTemplate); UserInfoTokenServices tokenServices = new UserInfoTokenServices(userInfoUri(), clientId); tokenServices.setRestTemplate(restTemplate); filter.setTokenServices(tokenServices); return filter; } @Bean public FilterRegistrationBean oauth2ClientFilterRegistration(OAuth2ClientAuthenticationProcessingFilter filter) { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(filter); registration.setOrder(-100); return registration; } @Value("${security.oauth2.client.user-info-uri}") private String userInfoUri; @Bean public String userInfoUri() { return userInfoUri; } } ``` 这些步骤可以帮助你自定义Spring Security OAuth2密码模式的登录路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值