spring|Spring Security 实现数据库登陆判断以及主界面获取用户名

  1. 一个简单的前端登陆界面
    Title
    用户名:
    密 码:

  2. Secrity 配置类
    package com.yang.config; import com.yang.service.UserLoginDetailsService; import com.yang.utils.Constants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; 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 public class SecurityConfig extends WebSecurityConfigurerAdapter {@Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }@Autowired // 装配自定义的用户登陆信息处理器 private UserLoginDetailsService userLoginDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); // auth.inMemoryAuthentication() //.passwordEncoder(encoder) //// withUser 必须要有 roles,不然报错 //.withUser("admin").password(encoder.encode("123123")).roles("admin"); // 使用自定义处理器 auth.userDetailsService(userLoginDetailsService).passwordEncoder(passwordEncoder()); }@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .mvcMatchers("/admin") .hasAnyRole(Constants.SMBMS_ADMIN, Constants.SMBMS_MANAGER, Constants.SMBMS_EMPLOYEE) ; http.formLogin() .usernameParameter("username")// 拦截用户名字段 .passwordParameter("password")// 拦截密码字段 .loginPage("/login")// 使用自己的登陆界面,即第1点的登陆界面 .loginProcessingUrl("/login.do")// 自定义要接收的请求 .defaultSuccessUrl("/admin")// 请求Controller .failureUrl("/error") ; http.logout() // 接收post请求的logout .logoutUrl("/logout.do") .logoutSuccessUrl("/") ; } }

  3. 自定义用户信息处理器
    package com.yang.service; import com.yang.pojo.LoginUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import java.util.ArrayList; @Component // 自定义处理器需要实现 UserDetailsService 接口 public class UserLoginDetailsService implements UserDetailsService {@Autowired @Qualifier("userServiceImpl") private UserService userService; // 用户业务,用于查询账号@Autowired private PasswordEncoder passwordEncoder; // 密码加密@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // 查询用户 LoginUser user = userService.login(username); System.out.println(user); if (user == null) { throw new UsernameNotFoundException("用户名不存在"); }String role = user.getRoleCode(); ArrayList roles = new ArrayList<>(); // 权限前需要添加“ROLE_” roles.add(new SimpleGrantedAuthority("ROLE_" + role)); // 用户名设置为昵称而不是账号id,让主界面可以获取到用户名 // org.springframework.security.core.userdetails.User return new User(user.getUserName(), passwordEncoder.encode(user.getUserPassword()), roles); } }

  4. 主界面Controller返回用户名
    package com.yang.controller; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class AdminController {// 即Security中defaultSuccessUrl指定的请求 @RequestMapping("/admin") public String admin(Model model) { // 获取Security中的用户名 // SecurityContextHolder.getContext().getAuthentication().getName() Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); model.addAttribute("name", authentication.getName()); return "admin"; } }

    【spring|Spring Security 实现数据库登陆判断以及主界面获取用户名】

    推荐阅读