Java登录的逻辑_Spring security登录过程逻辑详解

1. 新建项目

引入web和security包

完整的pom.xml文件如下

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.2.6.RELEASE

com.example

spring-demo

0.0.1-SNAPSHOT

spring-demo

Demo project for Spring Boot

1.8

org.springframework.boot

spring-boot-starter-security

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-test

test

org.junit.vintage

junit-vintage-engine

org.springframework.security

spring-security-test

test

org.springframework.boot

spring-boot-maven-plugin

2. 编写启动类和控制器方法和自定义登录页面

package com.example.springdemo;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

@SpringBootApplication

public class SpringDemoApplication {

public static void main(String[] args) {

SpringApplication.run(SpringDemoApplication.class, args);

}

@GetMapping("/")

public String hello() {

return "hello spring security";

}

}

Title

3. 编写配置类

package com.example.springdemo.conf;

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.core.Authentication;

import org.springframework.security.core.AuthenticationException;

import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import java.io.PrintWriter;

@EnableWebSecurity

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override

protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests()

.anyRequest().authenticated()

.and()

.formLogin()

//指定处理登录页面

.loginPage("/myLogin.html")

//指定登录成功的处理逻辑

.successHandler(new AuthenticationSuccessHandler() {

@Override

public void onAuthenticationSuccess(HttpServletRequest request,

HttpServletResponse response,

Authentication authentication)

throws IOException, ServletException {

response.setContentType("application/json;charset=UTF-8");

PrintWriter writer = response.getWriter();

writer.write("{\"error_code\":\"0\",\"message\":\"欢迎登录\"}");

}

})

//指定登录失败时的处理逻辑

.failureHandler(new AuthenticationFailureHandler() {

@Override

public void onAuthenticationFailure(HttpServletRequest request,

HttpServletResponse response,

AuthenticationException e)

throws IOException, ServletException {

response.setStatus(401);

PrintWriter writer = response.getWriter();

writer.write("{\"error_code\":\"401\",\"name\":\"" + e.getClass() + "\",\"message\":\"" + e.getMessage() + "\"}");

}

})

.permitAll()

.and()

.csrf().disable();

}

}

4. 运行结果

当输入密码错误时

1f9bc928fc635398bb92ea16307d8eea.png

当输入密码正确时

12eb01190e6f3b0f392bd60f1cfb1045.png

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的 Spring Security 登录验证的示例: 首先,在 pom.xml 中添加以下依赖: ``` <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.4.2</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.4.2</version> </dependency> ``` 接着,在 Spring 配置文件中添加以下配置: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/") .permitAll() .and() .logout() .permitAll(); } } ``` 上述代码中,我们配置了一个名为 SecurityConfig 的类,继承了 WebSecurityConfigurerAdapter 类。其中,我们注入了一个 UserDetailsService 的实现类,用于获取用户信息;并且创建了一个 PasswordEncoder 实例,用于加密密码。 在 configure(AuthenticationManagerBuilder auth) 方法中,我们将我们的 UserDetailsService 和 PasswordEncoder 注入到 AuthenticationManagerBuilder 中,用于验证用户身份。 在 configure(HttpSecurity http) 方法中,我们配置了登录页面、登录成功后跳转的页面等信息。 最后,我们需要实现 UserDetailsService 接口,例如: ``` @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserDao userDao; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userDao.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("用户不存在"); } return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), AuthorityUtils.createAuthorityList(user.getRole())); } } ``` 上述代码中,我们通过 UserDao 找到了指定用户名的 User 对象,并将其转换为 UserDetails 对象返回。这里需要注意的是,我们需要将 User 对象的角色转换为 AuthorityList,以便 Spring Security 进行权限验证。 这样,一个简单的 Spring Security 登录验证就完成了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值