作者 朱兆平

spring security 用户登录部分完成

... ... @@ -5,6 +5,7 @@
.mvn
/lib/
/xmlFromImf/
kakoRevice/
/errorLogs/
### STS ###
.apt_generated
... ...
#登录账号
loginname = NMMS
loginname = KAKO
#登录密码
loginpass = NMMS
loginpass = KAKO
#发送报文目录,相对程序目录
readDirectory = /Users/mrz/Downloads/1.woowo
readDirectory = /Users/mrz/Documents/java项目/test
#接收存储报文目录
bakDirectory = xmlFromImf
bakDirectory = kakoRevice
#是否需要发送报文,默认N不发,Y将发送readDirectory下的XML扩展名的报文
isNeedSend = N
isNeedSend = Y
#IMF MEAT报头配置
... ...
... ... @@ -30,6 +30,11 @@
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!--有WEBSOCKET包 包含了spring-boot-starter-web 和spring-boot-starter包 有这个包不要引入这俩包-->
<dependency>
<groupId>org.springframework.boot</groupId>
... ...
... ... @@ -6,9 +6,12 @@ package com.tianbo.warehouse;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@SpringBootApplication
@EnableScheduling
... ...
package com.tianbo.warehouse.controller;
import com.tianbo.warehouse.model.USERS;
import com.tianbo.warehouse.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class AdminController {
@Autowired
UserService userService;
@GetMapping("/admin")
public List<USERS> admin(){
return userService.selectAllUser();
}
}
... ...
package com.tianbo.warehouse.controller;
import com.tianbo.warehouse.model.PERMISSION;
import com.tianbo.warehouse.model.USERS;
import com.tianbo.warehouse.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class ImfLog {
@Autowired
UserService userService;
@RequestMapping("/log/imf")
public String IMFlog(){
return "log/imf";
... ... @@ -24,15 +32,11 @@ public class ImfLog {
return "home";
}
@RequestMapping("/admin")
@RequestMapping("/logs")
@ResponseBody
public String Admin(){
return "hello admin";
}
@RequestMapping("/login")
public String login(){
return "login";
public List<USERS> logs(){
List<USERS> usersList =userService.selectAllUser();
return usersList;
}
}
... ...
... ... @@ -11,7 +11,8 @@ public class IndexController {
@GetMapping("index")
public String index(){
return "数据仓库接收,落地报文给新舱单";
return "forward:/login";
// return "数据仓库接收,落地报文给新舱单";
}
... ...
package com.tianbo.warehouse.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class Login {
@RequestMapping("/login")
public String login(){
return "login";
}
}
... ...
package com.tianbo.warehouse.controller;
import com.tianbo.warehouse.model.USERS;
import com.tianbo.warehouse.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class MainController {
@Autowired
UserService userService;
@GetMapping("/error")
public List<USERS> error(){
List<USERS> usersList =userService.selectAllUser();
return usersList;
}
@GetMapping("/main")
public List<USERS> me(){
List<USERS> usersList =userService.selectAllUser();
return usersList;
}
}
... ...
... ... @@ -20,4 +20,6 @@ public interface USERSMapper {
int updateByPrimaryKey(USERS record);
List<USERS> selectAllUser();
}
\ No newline at end of file
... ...
... ... @@ -9,8 +9,7 @@ import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.xml.sax.SAXParseException;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.io.*;
import java.util.Iterator;
import java.util.List;
... ...
package com.tianbo.warehouse.model;
import org.springframework.security.core.GrantedAuthority;
import java.math.BigDecimal;
public class PERMISSION {
public class PERMISSION implements GrantedAuthority{
private static final long serialVersionUID = -3957539165716897200L;
private BigDecimal permissionId;
private String permissionName;
... ... @@ -52,4 +57,9 @@ public class PERMISSION {
public void setGroupName(String groupName) {
this.groupName = groupName == null ? null : groupName.trim();
}
@Override
public String getAuthority(){
return this.getPermissionName();
}
}
\ No newline at end of file
... ...
... ... @@ -4,9 +4,9 @@ import org.springframework.security.core.GrantedAuthority;
import java.math.BigDecimal;
public class ROLE implements GrantedAuthority{
public class ROLE{
private static final long serialVersionUID = -3957539165716897200L;
private BigDecimal roleId;
... ... @@ -48,8 +48,5 @@ public class ROLE implements GrantedAuthority{
this.description = description == null ? null : description.trim();
}
@Override
public String getAuthority(){
return this.getRoleName();
}
}
\ No newline at end of file
... ...
... ... @@ -37,6 +37,8 @@ public class USERS implements UserDetails{
private List<ROLE> roles;
private List<PERMISSION> permissions;
public BigDecimal getUserId() {
return userId;
}
... ... @@ -127,6 +129,13 @@ public class USERS implements UserDetails{
this.roles = roles;
}
public List<PERMISSION> getPermissions() {
return permissions;
}
public void setPermissions(List<PERMISSION> permissions) {
this.permissions = permissions;
}
@Override
public boolean isAccountNonExpired(){
return true;
... ... @@ -150,9 +159,9 @@ public class USERS implements UserDetails{
@Override
public Collection<? extends GrantedAuthority> getAuthorities(){
List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
List<ROLE> roles = this.getRoles();
for (ROLE role : roles) {
auths.add(new SimpleGrantedAuthority(role.getAuthority()));
List<PERMISSION> permissions = this.getPermissions();
for (PERMISSION permission : permissions) {
auths.add(new SimpleGrantedAuthority(permission.getAuthority()));
}
return auths;
}
... ...
... ... @@ -24,7 +24,7 @@ public class IMF_Task {
public static String isNeedSend = "N";
@Scheduled(fixedRate = 5000)
// @Scheduled(fixedRate = 5000)
private static void start() throws Exception {
PropertyConfigurator.configure("config/log4j.properties");
client = IMFClientFactory.createInstance();
... ... @@ -41,6 +41,7 @@ public class IMF_Task {
//启动读取线程
if (client != null) {
IMF_Reader reader = new IMF_Reader(client);
if (!IMF_Reader.isrunning) {
reader.start();
logger.info("*********读取线程已开启***********");
... ...
package com.tianbo.warehouse.security;
import com.tianbo.warehouse.dao.PERMISSIONMapper;
import com.tianbo.warehouse.dao.USERSMapper;
import com.tianbo.warehouse.model.PERMISSION;
import com.tianbo.warehouse.model.USERS;
import com.tianbo.warehouse.service.UserService;
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;
... ... @@ -22,26 +16,12 @@ public class CustomUserDetailService implements UserDetailsService {
@Autowired
UserService userService;
@Autowired
PERMISSIONMapper permissionMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
try {
USERS user = userService.loadByUsername(username);
//这里是根据用户ID取的权限表,还可以根据用户ID 去角色表
List<PERMISSION> permissions = permissionMapper.findByUserId(user.getUserId());
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
for (PERMISSION permission : permissions) {
if (permission != null && permission.getPermissionName() != null) {
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getPermissionName());
//1:此处将权限信息添加到 GrantedAuthority 对象中,在后面进行全权限验证时会使用GrantedAuthority 对象。
grantedAuthorities.add(grantedAuthority);
}
}
return user;
} catch (UsernameNotFoundException e) {
... ...
package com.tianbo.warehouse.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
... ... @@ -21,29 +21,48 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private PasswordEncoder passwordEncoder;
@Bean
UserDetailsService customUserService(){ //注册UserDetailsService 的bean
return new CustomUserDetailService();
}
@Qualifier("customuserservice")
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//user Details Service验证
auth.userDetailsService(customUserService()).passwordEncoder(passwordEncoder);
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated() //任何请求,登录后可以访问
.antMatchers("/admin","/role").authenticated()
//管理页面只允许管理员角色访问 //任何请求,登录后可以访问
.anyRequest().permitAll() //其余的不需要验证
.and()
.formLogin()
.loginProcessingUrl("/home")
.passwordParameter("password")
.usernameParameter("username")
//.loginProcessingUrl("/home")//登陆提交的处理url
.loginPage("/login")
.failureUrl("/login?error")
.permitAll() //登录页面用户任意访问
.failureUrl("/error")
.permitAll()//登录页面用户任意访问
.successForwardUrl("/main")
.and()
.logout()
.logoutSuccessUrl("/?logout=true")
.permitAll()
.and()
.logout().permitAll(); //注销行为任意访问
http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class);
.rememberMe()
.tokenValiditySeconds(604800)
//记住我功能,cookies有限期是一周
.rememberMeParameter("remeberme")
//登陆时是否激活记住我功能的参数名字,在登陆页面有展示
.rememberMeCookieName("workspace")
//cookies的名字,登陆后可以通过浏览器查看cookies名字
.and()
.cors()
.and()
.csrf().disable();
//http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class).csrf().disable();
}
}
... ...
... ... @@ -2,6 +2,9 @@ package com.tianbo.warehouse.service;
import com.tianbo.warehouse.model.USERS;
import java.util.List;
public interface UserService {
USERS loadByUsername(String username);
List<USERS> selectAllUser();
}
... ...
package com.tianbo.warehouse.service.imp;
import com.tianbo.warehouse.dao.PERMISSIONMapper;
import com.tianbo.warehouse.dao.ROLEMapper;
import com.tianbo.warehouse.dao.USERSMapper;
import com.tianbo.warehouse.model.PERMISSION;
import com.tianbo.warehouse.model.ROLE;
import com.tianbo.warehouse.model.USERS;
import com.tianbo.warehouse.service.UserService;
... ... @@ -19,6 +21,9 @@ public class UserServiceImpl implements UserService{
@Autowired
private ROLEMapper roleMapper;
@Autowired
private PERMISSIONMapper permissionMapper;
@Override
public USERS loadByUsername(String username){
List<USERS> userList = usersMapper.selectByUsername(username);
... ... @@ -26,13 +31,35 @@ public class UserServiceImpl implements UserService{
if (userList != null && userList.size() > 0) {
USERS user = userList.get(0);
List<PERMISSION> permissionList = permissionMapper.findByUserId(user.getUserId());
if (permissionList!=null && permissionList.size()>0){
user.setPermissions(permissionList);
}
List<ROLE> roleList = roleMapper.findRolesByUserId(user.getUserId());
if (roleList!=null && roleList.size()>0){
user.setRoles(roleList);
return user;
}
return user;
}
return null;
}
@Override
public List<USERS> selectAllUser(){
List<USERS> list = usersMapper.selectAllUser();
for (USERS user: list) {
List<PERMISSION> permissionList = permissionMapper.findByUserId(user.getUserId());
if (permissionList!=null && permissionList.size()>0){
user.setPermissions(permissionList);
}
List<ROLE> roleList = roleMapper.findRolesByUserId(user.getUserId());
if (roleList!=null && roleList.size()>0){
user.setRoles(roleList);
}
}
return list;
}
}
... ...
... ... @@ -25,6 +25,7 @@ public class MakeImfMeta {
meta.addElement("STYP").addText(STYP);
SAXReader saxReader = new SAXReader();
// saxReader.setEncoding("gb2312");
Document doc = saxReader.read(Content);
Element contentRoot = doc.getRootElement();
root.add(contentRoot);
... ...
... ... @@ -41,10 +41,14 @@ spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
spring.datasource.druid.default-auto-commit=true
#security配置
trace=true
mybatis.mapper-locations=classpath:mapping/*.xml
mybatis.type-aliases-package=com.tianbo.warehouse.model
logging.level.com.tianbo.warehouse.dao=DEBUG
logging.level.org.springframework.security =debug
debug=true
pagehelper.helper-dialect=oracle
#pagehelper.auto-dialect=true
#pagehelper.auto-runtime-dialect=true
... ...
... ... @@ -23,13 +23,33 @@
from PERMISSION
</select>
<select id="findByUserId" parameterType="java.math.BigDecimal" resultMap="BaseResultMap">
select p.*
from USERS u
LEFT JOIN USER_ROLE ur on u.user_id= ur.user_id
LEFT JOIN ROLE r on ur.role_id=r.role_id
LEFT JOIN ROLE_PERMISSION rp on rp.role_id=r.role_id
LEFT JOIN PERMISSION p on p.PERMISSION_ID =rp.permission_id
where u.USER_ID = #{userId,jdbcType=DECIMAL}
SELECT
P .*
FROM
PERMISSION P
WHERE
P .PERMISSION_ID IN (
SELECT
RP.permission_id
FROM
ROLE_PERMISSION RP
WHERE
RP.role_id IN (
SELECT
R.ROLE_ID
FROM
ROLE R
WHERE
R.ROLE_ID IN (
SELECT
UR.ROLE_ID
FROM
USER_ROLE UR
WHERE
UR.USER_ID = #{userId,jdbcType=DECIMAL}
)
)
)
</select>
<delete id="deleteByPrimaryKey" parameterType="java.math.BigDecimal" >
... ...
... ... @@ -24,10 +24,15 @@
where USER_ID = #{userId,jdbcType=DECIMAL}
</select>
<select id="selectByUsername" resultMap="BaseResultMap" parameterType="java.lang.String" >
select
<include refid="Base_Column_List" />
from USERS
where USERNAME = #{username,jdbcType=VARCHAR}
</select>
<select id="selectAllUser" resultMap="BaseResultMap" >
select
<include refid="Base_Column_List" />
from USERS
where USERNAME = #{username,jdbcType=VARCHAR}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.math.BigDecimal" >
delete from USERS
... ...
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta content="text/html;charset=UTF-8"/>
<title>登录页面</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}"/>
<style type="text/css">
body {
padding-top: 50px;
}
.starter-template {
padding: 40px 15px;
text-align: center;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">Spring Security演示</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a th:href="@{/}"> 首页 </a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div class="starter-template">
<p th:if="${param.logout}" class="bg-warning">已成功注销</p><!-- 1 -->
<p th:if="${param.error}" class="bg-danger">有错误,请重试</p> <!-- 2 -->
<h2>使用账号密码登录</h2>
<form name="form" th:action="@{/login}" action="/login" method="POST"> <!-- 3 -->
<div class="form-group">
<label for="username">账号</label>
<input type="text" class="form-control" name="username" value="" placeholder="账号" />
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" name="password" placeholder="密码" />
</div>
<input type="submit" id="login" value="Login" class="btn btn-primary" />
</form>
</div>
</div>
</body>
</html>
\ No newline at end of file
... ...
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta content="text/html;charset=UTF-8"/>
<title>错误页面</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}"/>
<style type="text/css">
body {
padding-top: 50px;
}
.starter-template {
padding: 40px 15px;
text-align: center;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">Spring Security演示</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a th:href="@{/}"> 首页 </a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="container">
</div>
</body>
</html>
\ No newline at end of file
... ...
... ... @@ -36,10 +36,10 @@
<div class="starter-template">
<h1 th:text="${msg.description}"></h1>
<p class="bg-primary" th:text="${msg.content}"></p>
<p class="bg-primary" th:text="${msg.description}"></p>
<div sec:authorize="hasRole('ROLE_HOME')"> <!-- 用户类型为ROLE_ADMIN 显示 -->
<p class="bg-info" th:text="${msg.etraInfo}"></p>
<p class="bg-info" th:text="${msg.description}"></p>
</div>
<div sec:authorize="hasRole('ROLE_ADMIN')"> <!-- 用户类型为ROLE_ADMIN 显示 -->
<p class="bg-info">恭喜您,您有 ROLE_ADMIN 权限 </p>
... ...
... ... @@ -44,6 +44,10 @@
<label for="password">密码</label>
<input type="password" class="form-control" name="password" placeholder="密码" />
</div>
<div class="form-group">
<label for="remeberme">记住我</label>
<input type="checkbox" name="remember-me" />
</div>
<input type="submit" id="login" value="Login" class="btn btn-primary" />
</form>
</div>
... ...