Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit cbf3f35

Browse files
加入shiro配置
1 parent 52d1535 commit cbf3f35

File tree

11 files changed

+233
-19
lines changed

11 files changed

+233
-19
lines changed

‎src/main/java/com/study/SpringbootShiroApplication.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@
33
import org.mybatis.spring.annotation.MapperScan;
44
import org.springframework.boot.SpringApplication;
55
import org.springframework.boot.autoconfigure.SpringBootApplication;
6+
import org.springframework.transaction.annotation.EnableTransactionManagement;
67
import org.springframework.web.bind.annotation.RequestMapping;
78
import org.springframework.web.bind.annotation.RestController;
89

9-
@RestController
1010
@SpringBootApplication
11+
@EnableTransactionManagement
1112
@MapperScan(basePackages = "com.study.mapper")
1213
public class SpringbootShiroApplication {
1314

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,53 @@
11
package com.study.config.shiro;
22

3-
import org.apache.shiro.authc.AuthenticationException;
4-
import org.apache.shiro.authc.AuthenticationInfo;
5-
import org.apache.shiro.authc.AuthenticationToken;
3+
import com.study.model.User;
4+
import com.study.service.UserService;
5+
import org.apache.shiro.SecurityUtils;
6+
import org.apache.shiro.authc.*;
67
import org.apache.shiro.authz.AuthorizationInfo;
78
import org.apache.shiro.realm.AuthorizingRealm;
9+
import org.apache.shiro.session.Session;
810
import org.apache.shiro.subject.PrincipalCollection;
11+
import org.apache.shiro.util.ByteSource;
12+
13+
import javax.annotation.Resource;
914

1015
/**
1116
* Created by yangqj on 2017年4月21日.
1217
*/
1318
public class MyShiroRealm extends AuthorizingRealm {
1419

20+
@Resource
21+
private UserService userService;
22+
23+
//授权
1524
@Override
1625
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
26+
User user= (User) SecurityUtils.getSubject().getPrincipal();
27+
System.out.println(user+"++++++++++++++++++++++++");//User{id=1, username='admin', password='3ef7164d1f6167cb9f2658c07d3c2f0a', enable=1}
1728
return null;
1829
}
1930

31+
//认证
2032
@Override
21-
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
22-
return null;
33+
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
34+
//获取用户的输入的账号.
35+
String username = (String)token.getPrincipal();
36+
User user = userService.selectByUsername(username);
37+
if(user==null) throw new UnknownAccountException();
38+
if (0==user.getEnable()) {
39+
throw new LockedAccountException(); // 帐号锁定
40+
}
41+
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
42+
user, //用户名
43+
user.getPassword(), //密码
44+
ByteSource.Util.bytes(username),
45+
getName() //realm name
46+
);
47+
// 当验证都通过后,把用户信息放在session里
48+
Session session = SecurityUtils.getSubject().getSession();
49+
session.setAttribute("userSession", user);
50+
session.setAttribute("userSessionId", user.getId());
51+
return authenticationInfo;
2352
}
2453
}
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
package com.study.config.shiro;
2+
3+
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
4+
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
5+
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
6+
import org.springframework.context.annotation.Bean;
7+
import org.springframework.context.annotation.Configuration;
8+
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
9+
import org.apache.shiro.mgt.SecurityManager;
10+
11+
import java.util.LinkedHashMap;
12+
import java.util.Map;
13+
14+
/**
15+
* Created by yangqj on 2017年4月23日.
16+
*/
17+
@Configuration
18+
public class ShiroConfig {
19+
20+
/**
21+
* ShiroFilterFactoryBean 处理拦截资源文件问题。
22+
* 注意:单独一个ShiroFilterFactoryBean配置是或报错的,因为在
23+
* 初始化ShiroFilterFactoryBean的时候需要注入:SecurityManager
24+
*
25+
Filter Chain定义说明
26+
1、一个URL可以配置多个Filter,使用逗号分隔
27+
2、当设置多个过滤器时,全部验证通过,才视为通过
28+
3、部分过滤器可指定参数,如perms,roles
29+
*
30+
*/
31+
@Bean
32+
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager){
33+
System.out.println("ShiroConfiguration.shirFilter()");
34+
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
35+
36+
// 必须设置 SecurityManager
37+
shiroFilterFactoryBean.setSecurityManager(securityManager);
38+
//拦截器.
39+
Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>();
40+
41+
//配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
42+
filterChainDefinitionMap.put("/logout", "logout");
43+
filterChainDefinitionMap.put("/static/**","anon");
44+
//<!-- 过滤链定义,从上向下顺序执行,一般将 /**放在最为下边 -->:这是一个坑呢,一不小心代码就不好使了;
45+
//<!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
46+
filterChainDefinitionMap.put("/user", "authc");
47+
filterChainDefinitionMap.put("/**", "authc");
48+
// 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
49+
shiroFilterFactoryBean.setLoginUrl("/login");
50+
// 登录成功后要跳转的链接
51+
shiroFilterFactoryBean.setSuccessUrl("/user");
52+
//未授权界面;
53+
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
54+
55+
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
56+
return shiroFilterFactoryBean;
57+
}
58+
59+
60+
@Bean
61+
public SecurityManager securityManager(){
62+
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
63+
//设置realm.
64+
securityManager.setRealm(myShiroRealm());
65+
return securityManager;
66+
}
67+
68+
@Bean
69+
public MyShiroRealm myShiroRealm(){
70+
MyShiroRealm myShiroRealm = new MyShiroRealm();
71+
myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());;
72+
return myShiroRealm;
73+
}
74+
75+
/**
76+
* 凭证匹配器
77+
* (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了
78+
* 所以我们需要修改下doGetAuthenticationInfo中的代码;
79+
* )
80+
* @return
81+
*/
82+
@Bean
83+
public HashedCredentialsMatcher hashedCredentialsMatcher(){
84+
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
85+
86+
hashedCredentialsMatcher.setHashAlgorithmName("md5");//散列算法:这里使用MD5算法;
87+
hashedCredentialsMatcher.setHashIterations(2);//散列的次数,比如散列两次,相当于 md5(md5(""));
88+
89+
return hashedCredentialsMatcher;
90+
}
91+
92+
93+
/**
94+
* 开启shiro aop注解支持.
95+
* 使用代理方式;所以需要开启代码支持;
96+
* @param securityManager
97+
* @return
98+
*/
99+
@Bean
100+
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
101+
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
102+
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
103+
return authorizationAttributeSourceAdvisor;
104+
}
105+
106+
}

‎src/main/java/com/study/controller/HomeController.java

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
package com.study.controller;
22

3+
import com.study.model.User;
4+
import org.apache.shiro.SecurityUtils;
5+
import org.apache.shiro.authc.AuthenticationException;
6+
import org.apache.shiro.authc.ExcessiveAttemptsException;
7+
import org.apache.shiro.authc.LockedAccountException;
8+
import org.apache.shiro.authc.UsernamePasswordToken;
9+
import org.apache.shiro.subject.Subject;
310
import org.springframework.stereotype.Controller;
11+
import org.springframework.ui.Model;
12+
import org.springframework.util.StringUtils;
413
import org.springframework.web.bind.annotation.RequestMapping;
514
import org.springframework.web.bind.annotation.RequestMethod;
615

@@ -18,7 +27,28 @@ public String login(){
1827
}
1928

2029
@RequestMapping(value="/login",method=RequestMethod.POST)
21-
public String login(HttpServletRequest request, Map<String, Object> map){
30+
public String login(HttpServletRequest request, User user, Model model){
31+
if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
32+
request.setAttribute("msg", "用户名或密码不能为空!");
33+
return "login";
34+
}
35+
Subject subject = SecurityUtils.getSubject();
36+
UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),user.getPassword());
37+
try {
38+
subject.login(token);
39+
return "redirect:user";
40+
}catch (LockedAccountException lae) {
41+
token.clear();
42+
request.setAttribute("msg", "用户已经被锁定不能登录,请与管理员联系!");
43+
return "login";
44+
} catch (AuthenticationException e) {
45+
token.clear();
46+
request.setAttribute("msg", "用户或密码不正确!");
47+
return "login";
48+
}
49+
}
50+
@RequestMapping("/user")
51+
public String user(){
2252
return "user/users";
2353
}
2454

‎src/main/java/com/study/model/User.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,4 +75,14 @@ public Integer getEnable() {
7575
public void setEnable(Integer enable) {
7676
this.enable = enable;
7777
}
78+
79+
@Override
80+
public String toString() {
81+
return "User{" +
82+
"id=" + id +
83+
", username='" + username + '\'' +
84+
", password='" + password + '\'' +
85+
", enable=" + enable +
86+
'}';
87+
}
7888
}

‎src/main/java/com/study/service/UserService.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,6 @@
88
*/
99
public interface UserService extends IService<User>{
1010
public PageInfo<User> selectByPage(User user, int start, int length);
11+
12+
public User selectByUsername(String username);
1113
}

‎src/main/java/com/study/service/impl/UserServiceImpl.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,16 @@ public PageInfo<User> selectByPage(User user, int start, int length) {
3535
List<User> userList = selectByExample(example);
3636
return new PageInfo<>(userList);
3737
}
38+
39+
@Override
40+
public User selectByUsername(String username) {
41+
Example example = new Example(User.class);
42+
Example.Criteria criteria = example.createCriteria();
43+
criteria.andEqualTo("username",username);
44+
List<User> userList = selectByExample(example);
45+
if(userList.size()>0){
46+
return userList.get(0);
47+
}
48+
return null;
49+
}
3850
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.study.util;
2+
3+
4+
import com.study.model.User;
5+
import org.apache.shiro.crypto.RandomNumberGenerator;
6+
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
7+
import org.apache.shiro.crypto.hash.SimpleHash;
8+
import org.apache.shiro.util.ByteSource;
9+
10+
public class PasswordHelper {
11+
private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
12+
private String algorithmName = "md5";
13+
private int hashIterations = 2;
14+
15+
public void encryptPassword(User user) {
16+
String salt=randomNumberGenerator.nextBytes().toHex();
17+
String newPassword = new SimpleHash(algorithmName, user.getPassword(), ByteSource.Util.bytes(user.getUsername()), hashIterations).toHex();
18+
user.setPassword(newPassword);
19+
}
20+
public static void main(String[] args) {
21+
PasswordHelper passwordHelper = new PasswordHelper();
22+
User user = new User();
23+
user.setUsername("admin");
24+
user.setPassword("admin");
25+
passwordHelper.encryptPassword(user);
26+
System.out.println(user);
27+
}
28+
}

‎src/main/resources/application.properties

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,7 @@
1+
debug=true
2+
logging.level.tk.mybatis=TRACE
3+
logging.level.org.springframework.web=DEBUG
14
# 数据源基础配置
2-
#druid.url=jdbc:mysql://localhost:3306/shiro
3-
#druid.driver-class=com.mysql.jdbc.Driver
4-
#druid.username=root
5-
#druid.password:root
6-
#druid.initial-size=1
7-
#druid.min-idle=1
8-
#druid.max-active=20
9-
#druid.test-on-borrow=true
105
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
116
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
127
spring.datasource.url=jdbc:mysql://localhost:3306/shiro
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
<div th:fragment="menu">
22
<div id="sidebar" >
33
<ul id="menu">
4-
<li><a href="users"><i class="icon icon-home"></i> <span>用户管理</span></a> </li>
5-
<li><a href="roles"><i class="icon icon-signal"></i> <span>角色管理</span></a> </li>
6-
<li><a href="resources"><i class="icon icon-inbox"></i> <span>资源管理</span></a> </li>
4+
<li><a href="user"><i class="icon icon-home"></i> <span>用户管理</span></a> </li>
5+
<li><a href="role"><i class="icon icon-signal"></i> <span>角色管理</span></a> </li>
6+
<li><a href="resource"><i class="icon icon-inbox"></i> <span>资源管理</span></a> </li>
77
</ul>
88
</div>
99
</div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /