SpringBoot2.0使用SpringSecurity安全框架实现登陆、权限

记录遇到的坑:SpringSecurity无法登陆

1、User类实现了UserDetails,自动生成的方法时,生成

	@Override
	public boolean isAccountNonExpired() {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public boolean isAccountNonLocked() {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public boolean isCredentialsNonExpired() {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public boolean isEnabled() {
		// TODO Auto-generated method stub
		return false;
	}

然后尝试登陆,一直登录失败,断点去看,发现check时账号已锁定

SpringBoot2.0使用SpringSecurity安全框架实现登陆、权限_第1张图片

看着isAccountNonLocked那么熟悉,回到User类去看,才发现自动生成的是false,修改为true就可以正常验证了。

2、抛出异常java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"

根据网上介绍应该是升级Security导致的问题

解决方法:

创建MyPasswordEncoder类

package com.nl.security;
 
import org.springframework.security.crypto.password.PasswordEncoder;
 
public class MyPasswordEncoder implements PasswordEncoder{
 
	@Override
	public String encode(CharSequence rawPassword) {
		// TODO Auto-generated method stub
		return rawPassword.toString();
	}
 
	@Override
	public boolean matches(CharSequence rawPassword, String encodedPassword) {
		// TODO Auto-generated method stub
		return encodedPassword.equals(rawPassword.toString());
	}
	
}

在SecurityConfig中验证部分添加

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserService())
        	.passwordEncoder(new MyPasswordEncoder());
    }

项目结构:SpringBoot2.0使用SpringSecurity安全框架实现登陆、权限_第2张图片

完整代码:

pom



	4.0.0
 
	com.damionew
	neightlight
	0.0.1-SNAPSHOT
	jar
 
	neightlight
	Demo project for Spring Boot
 
	
		org.springframework.boot
		spring-boot-starter-parent
		2.0.0.RELEASE
		 
	
 
	
		UTF-8
		UTF-8
		1.8
	
 
	
	          
          
            org.springframework.boot  
            spring-boot-starter-web  
              
                  
                    org.springframework.boot  
                    spring-boot-starter-logging  
                  
              
        
		
			org.springframework.boot
			spring-boot-starter-jdbc
		
 		
			org.springframework.boot
			spring-boot-starter-security
		
		
			org.springframework.boot
			spring-boot-starter-thymeleaf
		
		
			org.springframework.boot
			spring-boot-starter-websocket
		
 
		
			mysql
			mysql-connector-java
			runtime
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		
			org.springframework.security
			spring-security-test
			test
		

		
			com.alibaba
			druid
			1.1.5
		
		
		    org.mybatis.spring.boot
		    mybatis-spring-boot-starter
		    1.3.2
		

		
	    	org.springframework.boot
	    	spring-boot-devtools
	    	provided
	      
	    	true
	    
		
			org.slf4j
			slf4j-api
			
		
			org.slf4j
			slf4j-log4j12
			
	
 
	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
	            
	            
	              org.springframework
	              springloaded
	              1.2.6.RELEASE
	            
	          
	          
	            cn.springboot.Mainspringboot
	          
	          
		
	
 
 

login.html





Insert title here


账号 密码

LoginController

package com.nl.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginController {
	
//	@RequestMapping("/loginPage")
//	public String login() {
//		return "login";
//	}
	
	@RequestMapping("/loginFailure")
	public String loginFailure() {
		return "loginFailure";
	}
	@RequestMapping("/index")
	public String index() {
		return "index";
	}
}

user不仅要继承UserDetails,下面几个方法也是需要用到的,SpringSecurity自动调用,authorities用来存放权限

package com.nl.dao;
 
import java.io.Serializable;
import java.util.Collection;
 
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
 
public class User implements UserDetails,Serializable{
	int id;
	String username;
	String password;
	Collection authorities;
 
	public Collection getAuthorities() {
		return authorities;
	}
	public void setAuthorities(Collection authorities) {
		this.authorities = authorities;
	}
	public User() {
		
	}
	public User(Integer id,String username,String password) {
		this.id = id;
		this.username = username;
		this.password = password;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public boolean isAccountNonExpired() {
		// TODO Auto-generated method stub
		return true;
	}
	@Override
	public boolean isAccountNonLocked() {
		// TODO Auto-generated method stub
		return true;
	}
	@Override
	public boolean isCredentialsNonExpired() {
		// TODO Auto-generated method stub
		return true;
	}
	@Override
	public boolean isEnabled() {
		// TODO Auto-generated method stub
		return true;
	}
	
}

UserMapper.java

package com.nl.mapper;
 
import java.util.List;
import java.util.Map;
 
import org.apache.ibatis.annotations.Mapper;
 
import com.nl.dao.User;
@Mapper
public interface UserMapper {
	public User findUserByUserName(String username);
	public List> findUserRoleByUserName(String username);
}

MVCConfig

package com.nl.config;
 
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
 
@SuppressWarnings("deprecation")
@Configuration
public class MVCConfig extends WebMvcConfigurationSupport{
 
	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/login").setViewName("login");
	}
}

UserMapper.xml




	
	

以下是Security

WebSecurityConfig配置

package com.nl.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
 
import com.nl.security.CustomUserDetailsService;
import com.nl.security.MyPasswordEncoder;
 
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
	@Bean
	UserDetailsService customUserService(){
		return new CustomUserDetailsService();
	}
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserService())
        	.passwordEncoder(new MyPasswordEncoder());
    }
    @Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.csrf()	//跨站
			.disable()	//关闭跨站检测
			.authorizeRequests()	//验证策略
				.anyRequest()	//所有请求
				.authenticated()	//需要验证
				.and()
			.formLogin()
				.loginPage("/login")
				.defaultSuccessUrl("/index")
				.failureUrl("/loginFailure")
				.permitAll()
				.and()
			.logout()
				.permitAll();
	}
}

customUserDetailService

package com.nl.security;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
 
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
 
import com.nl.dao.User;
import com.nl.mapper.UserMapper;
@Service
public class CustomUserDetailsService implements UserDetailsService{
	@Autowired
	UserMapper userMapper;
	Logger logger = Logger.getLogger(CustomUserDetailsService.class);
	/**
	 * 自定义用户登录
	 */
	@SuppressWarnings("unused")
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		logger.info("获取用户信息-->用户名为:"+username);
		User user = userMapper.findUserByUserName(username);
		if (user == null) {
			logger.info("获取用户信息"+username+"失败");
			throw new UsernameNotFoundException("用户名:"+username+"不存在");
		}
		Collection authorities = new ArrayList();
		List> roleList = userMapper.findUserRoleByUserName(username);
		
		for (Map role : roleList) {
			logger.info("获取用户权限-->"+role.get("role_code"));
			GrantedAuthority authority = new SimpleGrantedAuthority(role.get("role_code"));
			authorities.add(authority);
		}
		user.setAuthorities(authorities);
		logger.info("获取用户"+username+"信息成功!");
		return user;
	}
	
}

MyPasswordEncoder

package com.nl.security;
 
import org.springframework.security.crypto.password.PasswordEncoder;
 
public class MyPasswordEncoder implements PasswordEncoder{
 
	@Override
	public String encode(CharSequence rawPassword) {
		// TODO Auto-generated method stub
		return rawPassword.toString();
	}
 
	@Override
	public boolean matches(CharSequence rawPassword, String encodedPassword) {
		// TODO Auto-generated method stub
		return encodedPassword.equals(rawPassword.toString());
	}
	
}

数据库脚本

/*Table structure for table `nl_role` */
 
DROP TABLE IF EXISTS `nl_role`;
 
CREATE TABLE `nl_role` (
  `role_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '角色ID',
  `role_name` varchar(10) DEFAULT NULL COMMENT '角色名称',
  `role_code` varchar(10) DEFAULT NULL COMMENT '角色编码',
  `role_description` varchar(20) DEFAULT NULL COMMENT '角色描述',
  PRIMARY KEY (`role_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
 
/*Data for the table `nl_role` */
 
insert  into `nl_role`(`role_id`,`role_name`,`role_code`,`role_description`) values (1,'普通用户','ROLE_USER','最低权限'),(2,'管理员','ROLE_ADMIN','管理员权限');
 
/*Table structure for table `nl_user` */
 
DROP TABLE IF EXISTS `nl_user`;
 
CREATE TABLE `nl_user` (
  `user_id` int(10) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  `username` varchar(10) DEFAULT NULL COMMENT '用户名称',
  `password` varchar(10) DEFAULT NULL COMMENT '用户密码',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
 
/*Data for the table `nl_user` */
 
insert  into `nl_user`(`user_id`,`username`,`password`) values (1,'sa','1'),(2,'ww','1'),(3,'2','1'),(4,'22',NULL);
 
/*Table structure for table `nl_user_role` */
 
DROP TABLE IF EXISTS `nl_user_role`;
 
CREATE TABLE `nl_user_role` (
  `user_id` int(11) DEFAULT NULL COMMENT '用户ID',
  `user_role` varchar(10) DEFAULT NULL COMMENT '用户角色'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
/*Data for the table `nl_user_role` */
 
insert  into `nl_user_role`(`user_id`,`user_role`) values (1,'1'),(1,'2'),(2,'1');

 

你可能感兴趣的:(SpringBoot,SpringBoot使用说明书)