spring security 自定义登录 权限 数据库

来源:互联网 发布:手机直播网络加速器 编辑:程序博客网 时间:2024/05/01 02:52
<pre name="code" class="html"><?xml version="1.0" encoding="UTF-8"?><beans:beans xmlns="http://www.springframework.org/schema/security"       xmlns:beans="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/securityhttp://www.springframework.org/schema/security/spring-security-4.0.xsd">    <http >               <!--路径'/admin/*'需要权限ROLE_ADMIN-->        <intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')"/>        <!--以"/user"开头的所有路径需要ROLE_USER权限-->        <intercept-url pattern="/user/**" access="hasRole('ROLE_USER')" />        <!--制定自定义的登录路径为/login,登录后默认跳转/welcome-->        <form-login login-page="/loginadmin"  />        <!--指定使用默认登出页面,登出后跳转到/login?logout页面-->        <logout logout-url="/logout" logout-success-url="/loginadmin" delete-cookies="JSESSIONID"/>        <!--对于没有权限的页面跳转到/403路径-->        <access-denied-handler error-page="/403" />        <csrf disabled="true" />           <session-management>          <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />       </session-management>    </http>             <authentication-manager alias="myAuthenticationManager">           <authentication-provider user-service-ref="myUserDetailsService">                   < password-encoder ref="bcryptEncoder"/>                   </authentication-provider>  //bcrypt密码加密    <beans:bean id="bcryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" /></authentication-manager>        <beans:bean id="myUserDetailsService"          class="cn.myuserdetailserver.MyUserDetailsService"/>     //bcrypt密码加密    <beans:bean id="bcryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" /></beans:beans>

security.xml 放在WebContent下
<span style="font-family: Arial, Helvetica, sans-serif;">  </span>


web.xml引入spring security

  <filter>     <filter-name>springSecurityFilterChain</filter-name>     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  </filter>  <filter-mapping>     <filter-name>springSecurityFilterChain</filter-name>     <url-pattern>/*</url-pattern>  </filter-mapping> 

login.jsp

                <form action="<%=path %>/login" method="post"><table><tr><td>User:</td><td><input type='text' name="name" id="name"></td></tr><tr><td>Password:</td><td><input type='password' name="word" id="word" /><input type="hidden" name="word" id="word" /></td></tr><tr><td><input type="submit" value="login"/></td><td>${ERROR}<span href="#" id="password" style="display: none">密码错误</span></td></tr></table> </form>




Login.java 

@RequestMapping(value="/login")public @ResponseBody  String loginpostf(HttpServletRequest request,HttpServletResponse response,@RequestParam(value="name")String name,@RequestParam(value="word") String word) {String username = name;String password = word;if(getLast(username)){return "error";}if(getLast(password)){return "error";}String url = "login";System.out.println("username=" + username + "\n" + "password=" + password);        username = username.trim(); HttpSession session = request.getSession();         UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); try {            Authentication authentication = myAuthenticationManager.authenticate(authRequest);            SecurityContextHolder.getContext().setAuthentication(authentication);            session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());            System.out.println("SPRING_SECURITY_CONTEXT");            url = getUrl(authentication);        } catch (AuthenticationException ex) {         return "1";        } return "0";}//得到urlpublic String getUrl(Authentication authentication){  Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());          if (roles.contains("ROLE_ADMIN")){             System.out.println("管理员权限---------");              return "admin/admin";          }  return null;}​



public static void main(String args[]) {int t = 0;String password = "123456";System.out.println(password + " -> ");for (t = 1; t <= 10; t++) {    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();    String hashedPassword = passwordEncoder.encode(password);    System.out.println(hashedPassword);}}


自定义 spring userdetail实现类 对应security.xml的

   <authentication-manager alias="myAuthenticationManager">        <authentication-provider user-service-ref="myUserDetailsService"/>       <!-- <sec:password-encoder hash="md5">              <sec:salt-source user-property="myPasswordEncode" />          </sec:password-encoder>  -->            </authentication-manager>        <beans:bean id="myUserDetailsService"          class="cn.myuserdetailserver.MyUserDetailsService"/>

@Component  public class MyUserDetailsService implements UserDetailsService {      public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {          ArrayList<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();          List<Tourist> list = LoginDao.getuserdetail(s);        Iterator<Tourist> it = list.iterator();        while(it.hasNext()){        Tourist temp = it.next();            authorities.add(new SimpleGrantedAuthority(temp.getRole()));             return new User(s,temp.getPassword(),true,true,true,true,authorities);         }return null;    }           }  

login.jsp

   简单的表单提交即可


作者来自:http://www.liubingxu.cn/ckwzby?id=12

 


0 0