SpringSecurity学习笔记之五:认证用户

本文介绍了如何在Spring Security中添加自定义登录页面、启用HTTP Basic认证和Remember-me功能。通过formLogin()方法可以恢复默认登录界面,启用HTTP Basic认证只需调用httpBasic(),Remember-me功能则通过rememberMe()实现,使用Cookie存储token,过期时间为四周。退出功能默认已配置,通过POST请求"/logout"来实现。
摘要由CSDN通过智能技术生成

  如果我们使用如下的最简单的配置,那么就能无偿地得到一个登陆页面:

package spitter.config;
......
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
   }

  实际上,在重写configure(HttpSecurity)之前,我们都能使用一个简单却功能完备的登录页。但是,一旦重写了configure(HttpSecurity)方法,就是失去了这个简单的登录界面。不过,这个功能要找回也容易。我们只需要在configure(HttpSecurity)方法中,调用formLogin(),如下所示:

@Override
protected void configure(HttpSecurity http) throws Exception{
    http
      .formLogin()
       .and()
       .authorizeRequests()
         .antMatchers("/spitter/me").hasRole("SPITTER")
         .antMatchers(HttpMethod.POST,"/spittles").hasRole("SPITTER")
         .anyRequest().permitAll()
       .and()
         .requiresChannel()
         .antMatchers("/spitter/form").requiresSecure();   
}

  如果我们访问应用的“/login”链接或者导航到需要认证的页面,那么将会在浏览器中展现登录界面。这个界面在审美上没什么令人兴奋的,但是它却能实现所需的功能。

添加自定义的登录页
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Spitter</
  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值