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时账号已锁定

看着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());
    }

项目结构:

完整代码:

pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
 
	<groupId>com.damionew</groupId>
	<artifactId>neightlight</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
 
	<name>neightlight</name>
	<description>Demo project for Spring Boot</description>
 
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
 
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>
 
	<dependencies>
	        <!-- Spring Boot web依赖 -->  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-web</artifactId>  
            <exclusions>  
                <exclusion>  
                    <groupId>org.springframework.boot</groupId>  
                    <artifactId>spring-boot-starter-logging</artifactId>  
                </exclusion>  
            </exclusions>  
        </dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
 		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-websocket</artifactId>
		</dependency>
 
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</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>
<!-- 		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
			<version>1.5.8.RELEASE</version>
		</dependency> -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.5</version>
		</dependency>
		<dependency>
		    <groupId>org.mybatis.spring.boot</groupId>
		    <artifactId>mybatis-spring-boot-starter</artifactId>
		    <version>1.3.2</version>
		</dependency>
<!-- 		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
			<version>9.0.1</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.0</version>
		</dependency> -->
		<dependency>
	    	<groupId>org.springframework.boot</groupId>
	    	<artifactId>spring-boot-devtools</artifactId>
	    	<scope>provided</scope>
	      <!--optional我没弄明白,都说必须为true,但我测试true,false,不加都可以-->
	    	<optional>true</optional>
	    </dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			</dependency>
	</dependencies>
 
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			<dependencies>
	            <!-- spring热部署 -->
	            <dependency>
	              <groupId>org.springframework</groupId>
	              <artifactId>springloaded</artifactId>
	              <version>1.2.6.RELEASE</version>
	            </dependency>
	          </dependencies>
	          <configuration>
	            <mainClass>cn.springboot.Mainspringboot</mainClass>
	          </configuration>
	          </plugin>
		</plugins>
	</build>
 
 
</project>

login.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Insert title here</title>
</head>
<body>
<form action="/login" method="post">
账号<input type="text" name="username" id="username"/>
密码<input type="text" name="password" id="password"/>
<input type="submit" value="登录"></input>
</form>
 
</body>
</html>

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<GrantedAuthority> authorities;
 
	public Collection<GrantedAuthority> getAuthorities() {
		return authorities;
	}
	public void setAuthorities(Collection<GrantedAuthority> 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<Map<String, String>> 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

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.nl.mapper.UserMapper">
	<select id="findUserByUserName" resultType="com.nl.dao.User">
		select * from nl_user where username = #{username}
<!-- 		<where>
			<if test="username !=null and username !='' ">
				username = #{username}
			</if>
		</where> -->
	</select>
	<select id="findUserRoleByUserName" resultType="Map">
		SELECT 
		  nu.user_id,
		  nn.role_code
		FROM
		  nl_user nu 
		  LEFT JOIN ( SELECT * FROM nl_user_role nur LEFT JOIN nl_role nr ON nur.user_role = nr.role_id) nn ON nu.user_id = nn.user_id
		where nu.username = #{username}
	</select>
</mapper>

以下是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<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		List<Map<String, String>> roleList = userMapper.findUserRoleByUserName(username);
		
		for (Map<String, String> 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');

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值