springsecurity入门1-登陆角色验证

案例程序下载地址:https://github.com/snowlavenderlove/springsecurity.git

1.创建数据库springsecurity,并创建三张表,sys_user,sys_role,sys_user_role,并插入记录,图如下:

 2.创建项目springsecurityUserRole,创建时添加web、thymeleaf、jpa、security、mysql、mybatis框架,创建项目参考博文:https://blog.csdn.net/qq_37231511/article/details/90669242

3.在pom.xml中添加druid、logging依赖

		<dependency>
		    <groupId>commons-logging</groupId>
		    <artifactId>commons-logging</artifactId>
		    <version>1.2</version>
		</dependency>
		<dependency>
		    <groupId>com.alibaba</groupId>
		    <artifactId>druid</artifactId>
		    <version>1.1.17</version>
		</dependency>	

4.编辑application.properties


#mysql
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springsecurity
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456

#druid
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

#mybatis
mybatis.type-aliases-package=com.xue.repository.dao
mybatis.mapper-locations=classpath*:com/xue/repository/mapper/*.xml

5.通过mybatis-generator自动生成代码,参考博文:https://blog.csdn.net/qq_37231511/article/details/90692784,自动生成后如图:

 

6.创建service层,创建SysUserService、SysRoleService、SysUserRoleService,代码如图

SysUserService

package com.xue.service;

import com.xue.entity.model.SysUser;

public interface SysUserService {
	
	public SysUser selectUserByName(String username);
	
	public SysUser selectUserById(Integer id);

}

SysRoleService 

package com.xue.service;

import com.xue.entity.model.SysRole;

public interface SysRoleService {
	
	public SysRole selectRoleById(Integer id);

}

SysUserRoleService 

package com.xue.service;

import java.util.List;

import com.xue.entity.model.SysUserRole;

public interface SysUserRoleService {
	
	public List<SysUserRole> selectUserRoleByUserId(Integer userId);
	

}

7.创建Service层实现包:Impl,并创建SysUserServiceImpl、SysRoleServiceImpl、SysUserRoleServiceImpl,代码如下:

SysUserServiceImpl

package com.xue.service.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xue.entity.model.SysUser;
import com.xue.repository.dao.SysUserMapper;
import com.xue.service.SysUserService;
@Service
public class SysUserServiceImpl implements SysUserService {
	
	@Autowired
	private SysUserMapper sysUserMapper;

	@Override
	public SysUser selectUserByName(String username) {
		// TODO Auto-generated method stub
		return sysUserMapper.selectUserByName(username);
	}

	@Override
	public SysUser selectUserById(Integer id) {
		// TODO Auto-generated method stub
		return sysUserMapper.selectUserById(id);
	}
	
	

}

 SysRoleServiceImpl

 

package com.xue.service.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xue.entity.model.SysRole;
import com.xue.repository.dao.SysRoleMapper;

@Service
public class SysRoleServiceImpl implements com.xue.service.SysRoleService {
	
	@Autowired
	private SysRoleMapper sysRoleMapper;

	@Override
	public SysRole selectRoleById(Integer id) {
		// TODO Auto-generated method stub
		return sysRoleMapper.selectRoleById(id);
	}
	
	

}

SysUserRoleServiceImpl

package com.xue.service.Impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xue.entity.model.SysUserRole;
import com.xue.repository.dao.SysUserRoleMapper;
import com.xue.service.SysUserRoleService;
@Service
public class SysUserRoleServiceImpl implements SysUserRoleService {
	
	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;

	@Override
	public List<SysUserRole> selectUserRoleByUserId(Integer userId) {
		// TODO Auto-generated method stub
		return sysUserRoleMapper.selectUserRoleByUserId(userId);
	}
	
	

}

 8.编辑dao层,编辑SysUserMapper、SysRoleMapper、SysUserRoleMapper文件

SysUserMapper:在最后添加

    SysUser selectUserByName(String username);
    
    SysUser selectUserById(Integer id);

SysRoleMapper:在最后添加

    SysRole selectRoleById(Integer id);

SysUserRoleMapper:在最后添加

    List<SysUserRole> selectUserRoleByUserId(Integer userId);

9.编辑mapper,编辑SysUserMapper、SysRoleMapper、SysUserRoleMapper

SysUserMapper:在最后添加

  <select id="selectUserById">
      select * from sys_user where id = #{id}
  </select>

SysRoleMapper:在最后添加

  <select id="selectRoleById" resultMap="BaseResultMap">
      select * from sys_role where id = #{id}
  </select>

SysUserRoleMapper:在最后添加

  <select id="selectUserRoleByUserId" resultMap="BaseResultMap">
      select * from sys_user_role where user_id =#{userId}
  </select>

10.在src/main/resources/templates下创建home.html与login.html

home.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>首页</title>
</head>
<body>
<h1>登陆成功</h1>
<a href="/admin">拥有admin权限</a>
<a href="/user">拥有user权限</a>
<button onclick="window.location.href='/logout'">退出</button>
</body>
</html>

login.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
<h1 align="left">登陆</h1>
<form action="/login" method="post">
用户名:<input type="text" name="username"/>
密码:<input type="password" name="password"  />
<button type="submit">登陆</button>
</form>
</body>
</html>

11.创建Controller层,创建类LoginSecurityController

package com.xue.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginSecurityController {
	
	@RequestMapping("/")
	public String index(){
		
		return "home";
	}
	
	@RequestMapping("/login")
	public String login(){
		
		return "login";
	}
	
	/**
	 * @PreAuthorize作用:判断用户是否有指定权限,没有就不能访问
	 */
	
	
	@RequestMapping("/admin")
	@ResponseBody
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public String admin(){
		
		return "此权限为admin所有!";
	}
	
	@RequestMapping("/user")
	@ResponseBody
	@PreAuthorize("hasRole('ROLE_USER')")
	public String user(){
		
		return "此权限为user所有!";
	}


}

 12.创建security层,创建CustomUserDetailsService,WebSecurityConfig

CustomUserDetailsService

package com.xue.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

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.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.stereotype.Service;

import com.xue.entity.model.SysRole;
import com.xue.entity.model.SysUser;
import com.xue.entity.model.SysUserRole;
import com.xue.service.SysRoleService;
import com.xue.service.SysUserRoleService;
import com.xue.service.SysUserService;
@Service
public class CustomUserDetailsService implements UserDetailsService {

	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private SysRoleService sysRoleService;
	
	@Autowired
	private SysUserRoleService sysUserRoleService;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		
		
		Collection<GrantedAuthority> authorities = new ArrayList<>();
		//从数据库user表中查询登陆者用户信息
		SysUser user = sysUserService.selectUserByName(username);
		
		if(null == user){
			throw new UsernameNotFoundException("用户不存在");
		}
		//从数据库sys_user_role表中查询登陆者所对应的用户权限关联信息
		List<SysUserRole> userRoleList = sysUserRoleService.selectUserRoleByUserId(user.getId());
		
		for(SysUserRole datas:userRoleList){
			//根据用户权限关联信息表中的权限id,从数据库sys_role表中查询登陆者所对应权限
			SysRole role = sysRoleService.selectRoleById(datas.getRoleId());
			
			authorities.add(new SimpleGrantedAuthority(role.getName()));
		}
		
		
		return new User(user.getUsername(),user.getPassword(),authorities);
	}
	
	

}

WebSecurityConfig

package com.xue.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	
	@Autowired
	private CustomUserDetailsService customUserDetailsService;

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		// TODO Auto-generated method stub
		
		/**
		 * 密码的加密方式
		 */
		
        auth.userDetailsService(customUserDetailsService).passwordEncoder(new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return charSequence.toString();
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return s.equals(charSequence.toString());
            }
        });
		
		
		
		
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// TODO Auto-generated method stub
		/**
		 * .anyRequest().authenticated():设置所有请求都需通过认证才能访问
		 * .and():表示一个配置的结束
		 * .formLogin().loginPage("/login"):设置登陆页,loginPage中是对应controller中的登陆RequestMapping
		 * .defaultSuccessUrl("/").permitAll():设置登陆成功页
		 */
		
		http.authorizeRequests()
		.anyRequest().authenticated()
		.and()
		.formLogin().loginPage("/login")
		.defaultSuccessUrl("/").permitAll()
		.and()
		.logout().permitAll();
		
		/**
		 * 关闭csrf
		 */
		http.csrf().disable();
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		// TODO Auto-generated method stub

	}
	
	

}

13.编辑主程序类SpringsecurityUserRoleApplication

package com.xue;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.xue.repository.dao")
public class SpringsecurityUserRoleApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringsecurityUserRoleApplication.class, args);
	}

}

14.综上代码结构如图:

15.启动程序,在浏览器输入http://localhost:8080/login,用账号a密码123456登陆,登陆成功后如图

 16.点击拥有admin权限文字链接,没有权限则报错403

17. 点击拥有user权限文字链接,如图拥有权限

18.用admin账号登陆,则没有user权限

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章