Springboot实现自动登录的功能

目录:

      概念

      实现

      原理

一、概念

    自动登录是我们在软件开发时一个非常常见的功能,例如我们登录 QQ时,登录界面会有记住密码这个功能,下次进入qq会进行自动登录。
    浏览器的自动登录是指用户在登录成功后,在某一段时间内,如果用户关闭了浏览器并重新打开,或者服务器重启了,都不需要用户重新登录了,用户依然可以直接访问接口数据。
    那么应该如何实现呢,其实spring security已经提供了相应的支持。

二、实现

实战:
(1)创建spring工程,引入web和security的依赖。

pom.xml如下:

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-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>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

(2)创建security配置类,在配置授权路径时添加 .rememberMe().key(“自定义”)

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    PasswordEncoder passwordEncoder(){
        return  NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("fyf")
                .roles("admin")
                .password("123");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .rememberMe()
                //key的作用:后端服务器重启,用户的自动登录不受影响,默认情况,服务器一重启,前端要重新登录
                .key("250")
                .and()
                .csrf()
                .disable();
    }
}

(3)测试controller

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }
}

(4)测试。

输入http://localhost:8080/hello,默认的登录页面多了一个选项,就是记住我。接着我们输入用户名密码,并且勾选上记住我这个框,然后点击登录按钮执行登录操作,/hello接口访问成功;
在这里插入图片描述
然后关闭浏览器直接访问http://localhost:8080/hello,无需登录直接访问成功。
在这里插入图片描述
最后我们可以将服务器重启,再来访问hello接口,也是无需登录直接访问成功。

三、原理:

我们在登录时的表单提交参数如下,如果你的登录页面是自定义登录页面,则添加上RememberMe的key-value即可。
在这里插入图片描述
此外,登录成功之后,就会自动跳转到 hello 接口了。注意,系统访问 hello 接口的时候,携带的 cookie:
在这里插入图片描述
remember-me类似于一个token,当你登录成功后每次请求都会携带这个key,后端会判断你是哪个用户。remember-me是经过base64编码且通过md5加密过后的字符串,格式如下:

username + “:” + tokenExpiryTime + “:” + password + “:” + key

此时,有人会想一旦令牌丢失,别人就可以拿着这个令牌随意登录我们的系统了,这是一个非常危险的操作。所以我们还要进行自动登录的安全优化。

那么如何让我们的 RememberMe 功能更加安全呢?

可以采用 二次校验或者持久化令牌 来解决。

参考:安全优化

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot 可以通过多种方式实现登录功能,其中常用的方式是通过 Spring Security 框架实现。以下是一个基本的 Spring Boot + Spring Security 实现登录功能的示例: 1. 添加 Spring Security 的依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 配置 Spring Security 在 Spring Boot 应用的配置类中添加以下代码: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/login", "/register").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/") .permitAll() .and() .logout() .permitAll(); } } ``` 其中, - `@EnableWebSecurity` 表示启用 Spring Security。 - `userDetailsService` 是一个自定义的用户认证服务,用于查询用户信息。需要实现 `UserDetailsService` 接口并编写查询用户信息的方法。在上述代码中,使用了 `@Autowired` 注解注入了一个 `UserDetailsService` 实例。 - `configure(HttpSecurity http)` 方法用于配置 Spring Security 的安全策略。在示例中,配置了允许访问 `/login` 和 `/register` 页面,其他请求需要认证后才能访问;配置了使用表单登录,并指定了登录页面和登录成功后的默认跳转页面;配置了允许用户注销。 3. 编写登录页面和用户认证服务 编写登录页面和用户认证服务的具体实现需要根据具体的业务需求进行,这里不再赘述。 以上是一个基本的 Spring Boot + Spring Security 实现登录功能的示例。当用户访问需要认证的页面时,系统会自动跳转到登录页面,用户输入正确的用户名和密码后即可登录,系统会将用户信息存储在 session 中。在登录后的其他页面中,可以通过 `SecurityContextHolder.getContext().getAuthentication().getPrincipal()` 获取当前登录用户的信息。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值