Java后台框架篇--Springsecurity(二)

剩下的页面代码

本来想给这个demo的源码出来的,但是笔者觉得,通过这个教程一步一步读下来,并自己敲一遍代码,会比直接运行一遍demo印象更深刻,并且更容易理解里面的原理。

而且我的源码其实都公布出来了:

login.jsp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<% @page language= "java" import = "java.util.*" pageEncoding= "UTF-8" %> 
<!DOCTYPEhtmlPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<html> 
<head> 
<title>登录</title> 
</head> 
<body> 
     <form action = "j_spring_security_check" method= "POST"
     <table> 
         <tr> 
             <td>用户:</td> 
             <td><input type = 'text' name= 'j_username' ></td> 
         </tr> 
         <tr> 
             <td>密码:</td> 
             <td><input type = 'password' name= 'j_password' ></td> 
         </tr> 
         <tr> 
             <td><input name = "reset" type= "reset" ></td> 
             <td><input name = "submit" type= "submit" ></td> 
         </tr> 
     </table> 
     </form> 
</body> 
</html>

index.jsp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<% @page language= "java" import = "java.util.*" pageEncoding= "UTF-8" %>  
<% @taglib prefix= "sec" uri= "http://www.springframework.org/security/tags" %>  
<!DOCTYPEHTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 
<html> 
 
<head> 
 
<title>My JSP 'index.jsp' starting page</title>  
</head> 
 
<body> 
       <h3>这是首页</h3>欢迎 
     <sec:authentication property = "name" /> ! 
 
        
     <a href= "admin.jsp" >进入admin页面</a>  
     <a href= "other.jsp" >进入其它页面</a>  
</body> 
 
</html>

admin.jsp:

1
2
3
4
5
6
7
8
9
10
11
<% @page language= "java" import = "java.util.*" pageEncoding= "utf-8" %> 
<!DOCTYPEHTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<html> 
<head> 
<title>My JSP 'admin.jsp' starting page</title> 
</head> 
<body> 
     欢迎来到管理员页面. 
       
</body> 
</html>

accessDenied.jsp:

1
2
3
4
5
6
7
8
9
10
11
<%@page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<!DOCTYPEHTMLPUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"> 
< html
< head
< title >My JSP 'admin.jsp' starting page</ title
</ head
< body
     欢迎来到管理员页面. 
       
</ body
</ html >

other.jsp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
< html
   < head
     < base href="<%=basePath%>"> 
 
     < title >My JSP 'other.jsp' starting page</ title
 
     < meta http-equiv = "pragma" content = "no-cache"
     < meta http-equiv = "cache-control" content = "no-cache"
     < meta http-equiv = "expires" content = "0" >     
     < meta http-equiv = "keywords" content = "keyword1,keyword2,keyword3"
     < meta http-equiv = "description" content = "This is my page"
     <!--
     <link rel="stylesheet" type="text/css" href="styles.css">
     --> 
 
   </ head
 
   < body
     < h3 >这里是Other页面</ h3
   </ body
</ html >

项目图:

最后的话:

虽然笔者没给读者们demo,但是所有源码和jar包都在这个教程里面,为什么不直接给?笔者的目的是让读者跟着教程敲一遍代码,使印象深刻(相信做这行的都知道,同样一段代码,看过和敲过的区别是多么的大),所以不惜如此来强迫大家了。

由于笔者有经常上csdn博客的习惯,所以读者有什么不懂的(或者指教的),笔者尽力解答。

转载请标注本文链接:http://blog.csdn.net/u012367513/article/details/38866465

补充:

(2014年11月21日第一次补充):

第一点:

MyUserDetailService这个类负责的是只是获取登陆用户的详细信息(包括密码、角色等),不负责和前端传过来的密码对比,只需返回User对象,后会有其他类根据User对象对比密码的正确性(框架帮我们做)。

第二点:

记得MyInvocationSecurityMetadataSource这个类是负责的是获取角色与url资源的所有对应关系,并根据url查询对应的所有角色。

今天为一个项目搭安全架构时,第一,发现上面MyInvocationSecurityMetadataSource这个类的代码有个bug:

上面的代码中,将所有的对应关系缓存到resourceMap,key是url,value是这个url对应所有角色。

getAttributes方法中,只要匹配到一个url就返回这个url对应所有角色,不再匹配后面的url,问题来了,当url有交集时,就有可能漏掉一些角色了:如有两个 url ,第一个是 /** ,第二个是 /role1/index.jsp ,第一个当然需要很高的权限了(因为能匹配所有 url ,即可以访问所有 url ),假设它需要的角色是 ROLE_ADMIN (不是一般人拥有的),第二个所需的角色是 ROLE_1 。    当我用 ROLE_1 这个角色访问 /role1/index.jsp 时,在getAttributes方法中,当先迭代了 /** 这个url,它就能匹配 /role1/index.jsp 这个url,并直接返回 /** 这个url对应的所有角色(在这,也就ROLE_ADMIN)给MyAccessDecisionManager这个投票类,  MyAccessDecisionManager这个类中再对比 用户的角色 ROLE_1 ,就会发现不匹配。    最后,明明可以有权访问的 url ,却不能访问了。

第二,之前不是说缓存所有对应关系,需要读者自己写sessionFactory(因为在实例化这个类时,配置的sessionFactory可能还没实例化或dao还没加载好),既然这样,那笔者可以不在构造方法中加载对应关系,可以在第一次调用getAttributes方法时再加载(用静态变量缓存起来,第二次就不用再加载了,     注:其实这样不是很严谨,不过笔者这里的对应关系是不变的,单例性不需很强,更严谨的请参考笔者另一篇博文设计模式之单件模式)。

修改过的MyInvocationSecurityMetadataSource类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package com.lcy.bookcrossing.springSecurity; 
 
import java.util.ArrayList; 
import java.util.Collection; 
import java.util.HashMap; 
import java.util.HashSet; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Map; 
import java.util.Set; 
 
import javax.annotation.Resource; 
 
import org.springframework.security.access.ConfigAttribute; 
import org.springframework.security.access.SecurityConfig; 
import org.springframework.security.web.FilterInvocation; 
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; 
 
import com.lcy.bookcrossing.bean.RoleUrlResource; 
import com.lcy.bookcrossing.dao.IRoleUrlResourceDao; 
import com.lcy.bookcrossing.springSecurity.tool.AntUrlPathMatcher; 
import com.lcy.bookcrossing.springSecurity.tool.UrlMatcher; 
 
public class MyInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {  
     private UrlMatcher urlMatcher = new AntUrlPathMatcher();  
//  private static Map<String, Collection<ConfigAttribute>> resourceMap = null; 
 
     //将所有的角色和url的对应关系缓存起来 
     private static List<RoleUrlResource> rus = null
 
     @Resource 
     private IRoleUrlResourceDao roleUrlDao; 
 
     //tomcat启动时实例化一次 
     public MyInvocationSecurityMetadataSource() { 
//      loadResourceDefine();   
         }    
     //tomcat开启时加载一次,加载所有url和权限(或角色)的对应关系 
     /*private void loadResourceDefine() {
         resourceMap = new HashMap<String, Collection<ConfigAttribute>>(); 
         Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>(); 
         ConfigAttribute ca = new SecurityConfig("ROLE_USER");
         atts.add(ca); 
         resourceMap.put("/index.jsp", atts);  
         Collection<ConfigAttribute> attsno =new ArrayList<ConfigAttribute>();
         ConfigAttribute cano = new SecurityConfig("ROLE_NO");
         attsno.add(cano);
         resourceMap.put("/other.jsp", attsno);   
         }  */ 
 
     //参数是要访问的url,返回这个url对于的所有权限(或角色) 
     public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {  
         // 将参数转为url     
         String url = ((FilterInvocation)object).getRequestUrl();    
 
         //查询所有的url和角色的对应关系 
         if(rus == null){ 
         rus = roleUrlDao.findAll(); 
        
 
         //匹配所有的url,并对角色去重 
         Set<String> roles = new HashSet<String>(); 
         for(RoleUrlResource ru : rus){ 
             if (urlMatcher.pathMatchesUrl(ru.getUrlResource().getUrl(), url)) {  
                         roles.add(ru.getRole().getRoleName()); 
                 }      
        
         Collection<ConfigAttribute> cas = new ArrayList<ConfigAttribute>();  
         for(String role : roles){ 
             ConfigAttribute ca = new SecurityConfig(role); 
             cas.add(ca);  
        
         return cas; 
 
         /*Iterator<String> ite = resourceMap.keySet().iterator(); 
         while (ite.hasNext()) {         
             String resURL = ite.next();  
             if (urlMatcher.pathMatchesUrl(resURL, url)) { 
                 return resourceMap.get(resURL);         
                 }       
            
         return null;    */ 
         }   
     public boolean supports(Class<?>clazz) {  
             return true ;   
             }  
     public Collection<ConfigAttribute> getAllConfigAttributes() {  
         return null ;   
        
     }

以上代码,在getAttributes方法中缓存起所有的对应关系(可以使用依赖注入了),并匹配所有 url ,对角色进行去重(因为多个url可能有重复的角色),这样就能修复那个bug了。

转载请标注本文链接:http://blog.csdn.net/u012367513/article/details/38866465


(2014年12月10日第二次补充):

这次补充不是修上面的bug,而是添加新功能。

我们知道,上面的实现的登陆界面只能传递两个参数(j_username,j_password),而且是固定的。

总是有一个项目需求,我们的角色(ROLE_)不是很多,只需在登陆界面选择一种角色就行了,那么如何将角色类型传递到spring security呢,现在笔者对配置文件再修改修改:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<? xml version = "1.0" encoding = "UTF-8" ?> 
< b:beans xmlns = "http://www.springframework.org/schema/security" 
     xmlns:b = "http://www.springframework.org/schema/beans" 
     xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
                         http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"> 
 
  <!-- 配置不需要安全管理的界面 --> 
      < http pattern = "/jsp/css/**" security = "none" ></ http
      < http pattern = "/jsp/js/**" security = "none" ></ http
      < http pattern = "/jsp/images/**" security = "none" ></ http
      < http pattern = "/login.jsp" security = "none" /> 
      < http pattern = "/accessDenied.jsp" security = "none" /> 
          < http pattern = "/index.jsp" security = "none" /> 
 
         < http use-expressions = 'true' entry-point-ref = "myAuthenticationEntryPoint" access-denied-page = "/accessDenied.jsp"
 
                 <!-- 使用自己自定义的登陆认证过滤器 --> <!-- 这里一定要注释掉,因为我们需要重写它的过滤器 --> 
                 <!-- <form-login login-page="/login.jsp" 
                 authentication-failure-url="/accessDenied.jsp"     
         default-target-url="/index.jsp" 
                  /> --> 
                 <!--访问/admin.jsp资源的用户必须具有ROLE_ADMIN的权限 --> 
                 <!-- <intercept-url pattern="/admin.jsp" access="ROLE_ADMIN" /> --> 
                 <!--访问/**资源的用户必须具有ROLE_USER的权限 --> 
                 <!-- <intercept-url pattern="/**" access="ROLE_USER" /> --> 
                 < session-management
                         < concurrency-control max-sessions = "1" 
                                 error-if-maximum-exceeded = "false" /> 
                 </ session-management
 
                 <!-- 认证和授权 --> <!-- 重写登陆认证的过滤器,使我们可以拿到任何参数  --> 
                 < custom-filter ref = "myAuthenticationFilter" position = "FORM_LOGIN_FILTER"  /> 
                 < custom-filter ref = "myFilter" before = "FILTER_SECURITY_INTERCEPTOR" /> 
 
                  <!-- 登出管理 --> 
         < logout invalidate-session = "true" logout-url = "/j_spring_security_logout" /> 
 
         </ http
 
         <!-- 未登录的切入点 --> <!-- 需要有个切入点 --> 
     < b:bean id = "myAuthenticationEntryPoint" class = "org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"
         < b:property name = "loginFormUrl" value = "/login.jsp" ></ b:property
     </ b:bean
 
         <!-- 登录验证器:用户有没有登录的资格 --> <!-- 这个就是重写的认证过滤器 --> 
     < b:bean id = "myAuthenticationFilter" class = "com.lcy.springSecurity.MyAuthenticationFilter"
         < b:property name = "authenticationManager" ref = "authenticationManager" /> 
         < b:property name = "filterProcessesUrl" value = "/j_spring_security_check" /> 
         < b:property name = "authenticationSuccessHandler"
             < b:bean class = "org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler"
                 < b:property name = "defaultTargetUrl" value = "/index.jsp" /> 
             </ b:bean
         </ b:property
         < b:property name = "authenticationFailureHandler"
             < b:bean class = "org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"
                 < b:property name = "defaultFailureUrl" value = "/accessDenied.jsp" /> 
             </ b:bean
         </ b:property
     </ b:bean
 
         <!--一个自定义的filter,必须包含 authenticationManager,accessDecisionManager,securityMetadataSource三个属性,我们的所有控制将在这三个类中实现,解释详见具体配置 --> 
         < b:bean id = "myFilter" 
                 class = "com.lcy.springSecurity.MyFilterSecurityInterceptor"
                 < b:property name = "authenticationManager" ref = "authenticationManager" /> 
                 < b:property name = "accessDecisionManager" ref = "myAccessDecisionManagerBean" /> 
                 < b:property name = "securityMetadataSource" ref = "securityMetadataSource" /> 
         </ b:bean
         <!--验证配置,认证管理器,实现用户认证的入口,主要实现UserDetailsService接口即可 --> 
         < authentication-manager alias = "authenticationManager"
                 < authentication-provider user-service-ref = "myUserDetailService"
                         <!--如果用户的密码采用加密的话 <password-encoder hash="md5" /> --> 
                         <!-- <password-encoder hash="md5" /> --> 
                 </ authentication-provider
         </ authentication-manager
         <!--在这个类中,你就可以从数据库中读入用户的密码,角色信息,是否锁定,账号是否过期等 --> 
         < b:bean id = "myUserDetailService" class = "com.lcy.springSecurity.MyUserDetailService" /> 
         <!--访问决策器,决定某个用户具有的角色,是否有足够的权限去访问某个资源 --> 
         < b:bean id = "myAccessDecisionManagerBean" 
                 class = "com.lcy.springSecurity.MyAccessDecisionManager"
         </ b:bean
         <!--资源源数据定义,将所有的资源和权限对应关系建立起来,即定义某一资源可以被哪些角色访问 --> 
         < b:bean id = "securityMetadataSource" 
                 class = "com.lcy.springSecurity.MyInvocationSecurityMetadataSource" />  
 
  </ b:beans >

我现在的项目需要的是,角色只要管理员、教师、学生,所以MyAuthenticationFilter(重写的认证过滤器):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package com.lcy.springSecurity; 
 
import javax.annotation.Resource; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
import org.springframework.security.authentication.AuthenticationServiceException; 
import org.springframework.security.authentication.BadCredentialsException; 
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 
import org.springframework.security.core.Authentication; 
import org.springframework.security.core.AuthenticationException; 
import org.springframework.security.core.context.SecurityContextHolder; 
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 
 
import com.lcy.dao.IAdminDao; 
import com.lcy.dao.IStudentDao; 
import com.lcy.dao.ITeacherDao; 
import com.lcy.entity.Admin; 
import com.lcy.entity.Student; 
import com.lcy.entity.Teacher; 
 
public class MyAuthenticationFilter extends UsernamePasswordAuthenticationFilter { 
 
         private static final String USERNAME = "username"
         private static final String PASSWORD = "password"
 
         @Resource 
         private IStudentDao studentdao; 
         @Resource 
         private ITeacherDao teacherdao; 
         @Resource 
         private IAdminDao admindao; 
 
         @Override 
         public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { 
                 if (!request.getMethod().equals( "POST" )) { 
                         throw new AuthenticationServiceException( "Authentication method not supported: " + request.getMethod()); 
                
 
                 String username = obtainUsername(request); 
                 String password = obtainPassword(request); 
                 String roletype = request.getParameter( "roletype" ); 
 
                 username = username.trim(); 
 
                 UsernamePasswordAuthenticationToken authRequest = null
 
                 if (! "" .equals(roletype) || roletype != null ){ 
                         if ( "student" .equals(roletype)){ 
                                 Student stu = studentdao.findById(username); 
 
                                 //通过session把用户对象设置到session中 
                                 request.getSession().setAttribute( "session_user" , stu); 
 
                                 //将角色标志在username上 
                                 username = "stu" +username; 
 
                                 try
                                         if (stu == null || !stu.getPassword().equals(password)) { 
                                                 BadCredentialsException exception = new BadCredentialsException( "用户名或密码不匹配" ); 
                                                 throw exception; 
                                        
                                 } catch (Exception e) { 
                                         BadCredentialsException exception = new BadCredentialsException( "没有此用户" ); 
                                         throw exception; 
                                
 
                         } else if ( "teacher" .equals(roletype)){ 
                                 Teacher tea = teacherdao.findById(username); 
 
                                 //通过session把用户对象设置到session中 
                                 request.getSession().setAttribute( "session_user" , tea); 
 
                                 //将角色标志在username上 
                                 username = "tea" +username; 
 
                                 try
                                         if (tea == null || !tea.getPassword().equals(password)) { 
                                                 BadCredentialsException exception = new BadCredentialsException( "用户名或密码不匹配" ); 
                                                 throw exception; 
                                        
                                 } catch (Exception e) { 
                                         BadCredentialsException exception = new BadCredentialsException( "没有此用户" ); 
                                         throw exception; 
                                
 
                         } else if ( "admin" .equals(roletype)){ 
                                 Admin adm = admindao.findById(username); 
 
                                 //通过session把用户对象设置到session中 
                                 request.getSession().setAttribute( "session_user" , adm); 
 
                                 //将角色标志在username上 
                                 username = "adm" +username; 
                                 try
                                         if (adm == null || !password.equals(adm.getPassword())) { 
                                                 BadCredentialsException exception = new BadCredentialsException( "用户名或密码不匹配" ); 
                                                 throw exception; 
                                        
                                 } catch (Exception e) { 
                                         BadCredentialsException exception = new BadCredentialsException( "没有此用户" ); 
                                         throw exception; 
                                
 
                         } else
                                 BadCredentialsException exception = new BadCredentialsException( "系统错误:没有对应的角色!" ); 
                                 throw exception; 
                        
                
 
                 //实现验证 
                 authRequest = new UsernamePasswordAuthenticationToken(username, password); 
                 //允许设置用户详细属性 
                 setDetails(request, authRequest); 
                 //运行 
                 return this .getAuthenticationManager().authenticate(authRequest); 
        
 
         @Override 
         protected String obtainUsername(HttpServletRequest request) { 
                 Object obj = request.getParameter(USERNAME); 
                 return null == obj ? "" : obj.toString(); 
        
 
         @Override 
         protected String obtainPassword(HttpServletRequest request) { 
                 Object obj = request.getParameter(PASSWORD); 
                 return null == obj ? "" : obj.toString(); 
        
 
         @Override 
         protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) { 
                 super .setDetails(request, authRequest); 
        
}

笔者自己断点可知,执行完上面那个认证过滤器,才会执行MyUserDetailService。

注:因为 MyUserDetailService类中的loadUserByUsername(String username) 方法只能接收一个参数username,而且这个username是从认证过滤器那里传过来的,所以笔者就通过username顺带传递角色类型过来,如上面认证过滤器,将角色类型拼在username中。到MyUserDetailService类在解开。(如有更好的方法,请评论告知,谢谢)

MyUserDetailService:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.lcy.springSecurity; 
 
import java.util.ArrayList; 
import java.util.Collection; 
 
import javax.annotation.Resource; 
 
import org.springframework.dao.DataAccessException; 
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 com.lcy.dao.IAdminDao; 
import com.lcy.dao.IStudentDao; 
import com.lcy.dao.ITeacherDao; 
import com.lcy.entity.Admin; 
import com.lcy.entity.Student; 
import com.lcy.entity.Teacher; 
 
public class MyUserDetailService implements UserDetailsService {  
         @Resource 
         private IStudentDao studentdao; 
         @Resource 
         private ITeacherDao teacherdao; 
         @Resource 
         private IAdminDao admindao; 
 
         //登陆验证时,通过username获取用户的所有权限信息, 
         //并返回User放到spring的全局缓存SecurityContextHolder中,以供授权器使用 
         public UserDetails loadUserByUsername(String username)  
                         throws UsernameNotFoundException, DataAccessException {    
                 Collection<GrantedAuthority> auths= new ArrayList<GrantedAuthority>(); 
                 //获取角色标志 
                 String roletype = username.substring( 0 , 3 ); 
                 username = username.substring( 3 ); 
                 String password = ""
 
                 if ( "stu" .equals(roletype)){ 
                         Student stu = studentdao.findById(username); 
                         password = stu.getPassword(); 
                         auths.add( new SimpleGrantedAuthority( "ROLE_STU" )); 
                 } else if ( "tea" .equals(roletype)){ 
                         Teacher tea = teacherdao.findById(username); 
                         password = tea.getPassword(); 
                         auths.add( new SimpleGrantedAuthority( "ROLE_TEA" )); 
                 } else if ( "adm" .equals(roletype)){ 
                         Admin adm = admindao.findById(username); 
                         password = adm.getPassword(); 
                         auths.add( new SimpleGrantedAuthority( "ROLE_ADM" )); 
                
 
                 User user = new User(username, password, true , true , true , true , auths);  
                 return user;   
                 }  
         }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值