spring security实现authorization code模式,自定义登录页面,自动授权,自定义密码编码,跳转登录页面http转https

spring security实现authorization code模式# 系列文章目录

SpringSecurity实现OAuth2
JWT和OAuth2在SpringBoot下的实现



摘要

为了将老项目接口安全暴露给第三方,我采取了OAuth 2.0 authorization code技术给接口做了鉴权。以spring security authorization code模式,论述了OAuthServer程序中自定义资源的方法。在项目中采用自定义登录页面替换默认的login页面,来使样式UI与自己系统风格保持一致;采用设置自动授权,省去了登录成功后要点击approve二次确认;采用了自定义密码验证,对接老系统账号数据与老系统密码编码验证保持一致,相应client_secret密码编码替换;采用了跳转登录页面http转https,使登录页链接与服务器https环境一致。


自定义登录页面

自定义登录页面必须放到后端项目里,跟授权接口在一个域里。
如果这是你的登录页html
resources/static/login.html

<form action="./login.html" method="post">
  <div class="input">
    <label for="name">用户名</label>
    <input type="text" name="username" id="username">
    <span class="spin"></span>
  </div>
  <div class="input">
    <label for="pass">密码</label>
    <input type="password" name="password" id="password">
    <span class="spin"></span>
  </div>
  <div class="button login">
    <button type="submit">
      <span>登录</span>
      <i class="fa fa-check"></i>
    </button>
  </div>
</form>

需要在HttpSecurity方法里做相应配置

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http
                .formLogin().loginPage("/login.html")
                .permitAll()
                .and()
                .csrf().disable()
        ;
    }

在做如上配置后,spring security会自动映射默认的login接口为/login.html,登录页面的表单action也写为form action=“./login.html”。

自动授权

自动授权是在oauth_client_details表里autoapprove配置的。配置之后登录页数据账号密码验证成功就直接跳转到redirect_uri?code=xxxx。
在这里插入图片描述

自定义密码验证

先实现PasswordEncoder接口。
在实现并使用了自己实现的PasswordEncoder之后,client_secret也要用这种编码方式写入数据库。

public class CustomPasswordEncoder implements PasswordEncoder {
    private static Logger log = LoggerFactory.getLogger(CustomPasswordEncoder.class);
    @Override
    public String encode(CharSequence rawPassword) {
        return EncryptUtil.encodePassword(rawPassword.toString());
    }
/**
 rawPassword 数据来自表单输入;
 encodedPassword 数据来自UserDetailsService#loadUserByUsername;
 */
    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        if (encodedPassword == null || encodedPassword.length() == 0) {
            log.warn("Empty encoded password");
            return false;
        }
        
        return encode(rawPassword).equals(encodedPassword);
    }
}

在WebSecurityConfigurerAdapter中定义Encoder的bean就会使用。

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

记得修改UserDetailsService#loadUserByUsername方法。

跳转登录页面http转https

这里以springboot的tomcat为例。

server:
  tomcat:
    redirect-context-root: true
    remote-ip-header: x-forwarded-for
    protocol-header-https-value: https
    protocol-header: x-forwarded-proto

放出refresh token的endpoint

在AuthorizationServerConfigurerAdapter的继承类中配置:

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 设置令牌
        endpoints.tokenStore(tokenStore())
                .userDetailsService(userDetailsService); // 此配置是将refresh token放出来。
    }

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
嗨!关于Spring Boot整合Spring SecurityOAuth2.0实现token认证,你可以按照以下步骤进行操作: 1. 添加依赖:在你的Spring Boot项目的pom.xml文件中,添加Spring SecurityOAuth2.0相关的依赖。 ```xml <dependencies> <!-- Spring Security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- Spring Security OAuth2 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency> </dependencies> ``` 2. 配置Spring Security:创建一个继承自WebSecurityConfigurerAdapter的配置类,并重写configure方法来配置Spring Security的行为。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/oauth2/**", "/login/**", "/logout/**") .permitAll() .anyRequest() .authenticated() .and() .oauth2Login() .loginPage("/login") .and() .logout() .logoutSuccessUrl("/") .invalidateHttpSession(true) .clearAuthentication(true) .deleteCookies("JSESSIONID"); } } ``` 在上述配置中,我们允许访问一些特定的URL(如/oauth2/**,/login/**和/logout/**),并保护所有其他URL。我们还设置了自定义登录页面和注销成功后的跳转页面。 3. 配置OAuth2.0:创建一个继承自AuthorizationServerConfigurerAdapter的配置类,并重写configure方法来配置OAuth2.0的行为。 ```java @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients .inMemory() .withClient("client_id") .secret("client_secret") .authorizedGrantTypes("authorization_code", "password", "refresh_token") .scopes("read", "write") .accessTokenValiditySeconds(3600) .refreshTokenValiditySeconds(86400); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .authenticationManager(authenticationManager); } } ``` 在上述配置中,我们使用内存存储客户端信息(client_id和client_secret),并配置了授权类型(如authorization_code、password和refresh_token)。我们还设置了访问令牌和刷新令牌的有效期。 4. 创建登录页面:创建一个HTML登录页面,用于用户进行身份验证并获取访问令牌。 ```html <!DOCTYPE html> <html> <head> <title>Login</title> </head> <body> <h2>Login</h2> <form th:action="@{/login}" method="post"> <div> <label for="username">Username:</label> <input type="text" id="username" name="username" /> </div> <div> <label for="password">Password:</label> <input type="password" id="password" name="password" /> </div> <div> <button type="submit">Login</button> </div> </form> </body> </html> ``` 5. 处理登录请求:创建一个控制器来处理登录请求,并在登录成功后重定向到受保护的资源。 ```java @Controller public class LoginController { @GetMapping("/login") public String showLoginForm() { return "login"; } @PostMapping("/login") public String loginSuccess() { return "redirect:/protected-resource"; } } ``` 在上述控制器中,我们使用@GetMapping注解来处理GET请求,@PostMapping注解来处理POST请求。登录成功后,我们将用户重定向到受保护的资源。 这样,你就完成了Spring Boot整合Spring SecurityOAuth2.0实现token认证的配置。你可以根据自己的需求进行进一步的定制和扩展。希望对你有所帮助!如果你有任何疑问,请随时问我。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值