登录流程

1)容器启动(MySecurityMetadataSource:loadResourceDefine加载系统资源与权限列表)

 2)用户发出请求

 3)过滤器拦截(MySecurityFilter:doFilter)

 4)取得请求资源所需权限(MySecurityMetadataSource:getAttributes)

 5)匹配用户拥有权限和请求权限(MyAccessDecisionManager:decide),如果用户没有相应的权限,

执行第6步,否则执行第7步。

 6)登录

 7)验证并授权(MyUserDetailServiceImpl:loadUserByUsername)

1、web.xml中加入过滤器

  1. <!-- SpringSecurity 核心过滤器配置 -->
  2. <filter>
  3. <filter-name>springSecurityFilterChain</filter-name>
  4. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  5. </filter>
  6. <filter-mapping>
  7. <filter-name>springSecurityFilterChain</filter-name>
  8. <url-pattern>/*</url-pattern>
  9. </filter-mapping>
<!-- SpringSecurity 核心过滤器配置 -->
<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>

2、新建spring-security.xml文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans:beans xmlns="http://www.springframework.org/schema/security"
  3. xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd
  6. http://www.springframework.org/schema/security
  7. http://www.springframework.org/schema/security/spring-security.xsd">
  8. <!-- entry-point-ref 配置自定义登录 -->
  9. <http use-expressions="true" entry-point-ref="authenticationProcessingFilterEntryPoint">
  10. <!-- 登出配置 -->
  11. <logout logout-url="/j_spring_security_logout" logout-success-url="/login" />
  12. <access-denied-handler error-page="/noPower" />
  13. <!-- 过滤不被拦截的请求 -->
  14. <intercept-url pattern="/login*" access="permitAll" />
  15. <intercept-url pattern="/resources/**" access="permitAll" />
  16. <!-- 只有权限才能访问的请求 -->
  17. <intercept-url pattern="/admin/**" access="isAuthenticated()" />
  18. <custom-filter ref="loginFilter" position="FORM_LOGIN_FILTER" />
  19. <custom-filter ref="securityFilter" before="FILTER_SECURITY_INTERCEPTOR" />
  20. </http>
  21. <beans:bean id="loginFilter"
  22. class="cn.com.abel.test.service.security.MyUsernamePasswordAuthenticationFilter">
  23. <!-- 登录提交处理 -->
  24. <beans:property name="filterProcessesUrl" value="/j_spring_security_check"></beans:property>
  25. <!-- 登录成功跳转 -->
  26. <beans:property name="authenticationSuccessHandler"
  27. ref="loginLogAuthenticationSuccessHandler"></beans:property>
  28. <!-- 设置登录失败的网址 -->
  29. <beans:property name="authenticationFailureHandler"
  30. ref="simpleUrlAuthenticationFailureHandler"></beans:property>
  31. <!-- 用户拥有权限 -->
  32. <beans:property name="authenticationManager" ref="myAuthenticationManager"></beans:property>
  33. </beans:bean>
  34. <beans:bean id="loginLogAuthenticationSuccessHandler"
  35. class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
  36. <beans:property name="defaultTargetUrl" value="/admin/index"></beans:property>
  37. </beans:bean>
  38. <beans:bean id="simpleUrlAuthenticationFailureHandler"
  39. class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
  40. <beans:property name="defaultFailureUrl" value="/login"></beans:property>
  41. </beans:bean>
  42. <authentication-manager alias="myAuthenticationManager">
  43. <authentication-provider user-service-ref="myUserDetailServiceImpl">
  44. <password-encoder ref="encoder" />
  45. </authentication-provider>
  46. </authentication-manager>
  47. <beans:bean id="myUserDetailServiceImpl"
  48. class="cn.com.abel.test.service.security.AdminUserDetailServiceImpl">
  49. </beans:bean>
  50. <beans:bean id="authenticationProcessingFilterEntryPoint"
  51. class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
  52. <beans:property name="loginFormUrl" value="/login"></beans:property>
  53. </beans:bean>
  54. <!-- 认证过滤器 -->
  55. <beans:bean id="securityFilter"
  56. class="cn.com.abel.test.service.security.MySecurityFilter">
  57. <!-- 用户拥有的角色 -->
  58. <beans:property name="authenticationManager" ref="myAuthenticationManager" />
  59. <!-- 用户是否拥有所请求资源的权限 -->
  60. <beans:property name="accessDecisionManager" ref="myAccessDecisionManager" />
  61. <!-- 资源与角色的对应关系 -->
  62. <beans:property name="securityMetadataSource" ref="mySecurityMetadataSource" />
  63. <!-- <beans:property name="rejectPublicInvocations" value="true"/> -->
  64. </beans:bean>
  65. <beans:bean id="myAccessDecisionManager" class="myAccessDecisionManager"></beans:bean>
  66. <beans:bean id="mySecurityMetadataSource"
  67. class="cn.com.abel.test.service.security.MySecurityMetadataSource">
  68. <beans:constructor-arg>
  69. <beans:ref bean="resourceService" />
  70. </beans:constructor-arg>
  71. </beans:bean>
  72. <beans:bean id="encoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"></beans:bean>
  73. </beans:beans>
<?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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
&lt;!-- entry-point-ref 配置自定义登录 --&gt;
&lt;http use-expressions="true" entry-point-ref="authenticationProcessingFilterEntryPoint"&gt; &lt;!-- 登出配置 --&gt;
&lt;logout logout-url="/j_spring_security_logout" logout-success-url="/login" /&gt; &lt;access-denied-handler error-page="/noPower" /&gt; &lt;!-- 过滤不被拦截的请求 --&gt;
&lt;intercept-url pattern="/login*" access="permitAll" /&gt;
&lt;intercept-url pattern="/resources/**" access="permitAll" /&gt; &lt;!-- 只有权限才能访问的请求 --&gt;
&lt;intercept-url pattern="/admin/**" access="isAuthenticated()" /&gt; &lt;custom-filter ref="loginFilter" position="FORM_LOGIN_FILTER" /&gt;
&lt;custom-filter ref="securityFilter" before="FILTER_SECURITY_INTERCEPTOR" /&gt; &lt;/http&gt; &lt;beans:bean id="loginFilter"
class="cn.com.abel.test.service.security.MyUsernamePasswordAuthenticationFilter"&gt; &lt;!-- 登录提交处理 --&gt;
&lt;beans:property name="filterProcessesUrl" value="/j_spring_security_check"&gt;&lt;/beans:property&gt; &lt;!-- 登录成功跳转 --&gt;
&lt;beans:property name="authenticationSuccessHandler"
ref="loginLogAuthenticationSuccessHandler"&gt;&lt;/beans:property&gt; &lt;!-- 设置登录失败的网址 --&gt;
&lt;beans:property name="authenticationFailureHandler"
ref="simpleUrlAuthenticationFailureHandler"&gt;&lt;/beans:property&gt; &lt;!-- 用户拥有权限 --&gt;
&lt;beans:property name="authenticationManager" ref="myAuthenticationManager"&gt;&lt;/beans:property&gt;
&lt;/beans:bean&gt; &lt;beans:bean id="loginLogAuthenticationSuccessHandler"
class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler"&gt;
&lt;beans:property name="defaultTargetUrl" value="/admin/index"&gt;&lt;/beans:property&gt;
&lt;/beans:bean&gt;
&lt;beans:bean id="simpleUrlAuthenticationFailureHandler"
class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"&gt;
&lt;beans:property name="defaultFailureUrl" value="/login"&gt;&lt;/beans:property&gt;
&lt;/beans:bean&gt; &lt;authentication-manager alias="myAuthenticationManager"&gt;
&lt;authentication-provider user-service-ref="myUserDetailServiceImpl"&gt;
&lt;password-encoder ref="encoder" /&gt;
&lt;/authentication-provider&gt;
&lt;/authentication-manager&gt; &lt;beans:bean id="myUserDetailServiceImpl"
class="cn.com.abel.test.service.security.AdminUserDetailServiceImpl"&gt;
&lt;/beans:bean&gt; &lt;beans:bean id="authenticationProcessingFilterEntryPoint"
class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"&gt;
&lt;beans:property name="loginFormUrl" value="/login"&gt;&lt;/beans:property&gt;
&lt;/beans:bean&gt; &lt;!-- 认证过滤器 --&gt;
&lt;beans:bean id="securityFilter"
class="cn.com.abel.test.service.security.MySecurityFilter"&gt;
&lt;!-- 用户拥有的角色 --&gt;
&lt;beans:property name="authenticationManager" ref="myAuthenticationManager" /&gt;
&lt;!-- 用户是否拥有所请求资源的权限 --&gt;
&lt;beans:property name="accessDecisionManager" ref="myAccessDecisionManager" /&gt;
&lt;!-- 资源与角色的对应关系 --&gt;
&lt;beans:property name="securityMetadataSource" ref="mySecurityMetadataSource" /&gt;
&lt;!-- &lt;beans:property name="rejectPublicInvocations" value="true"/&gt; --&gt; &lt;/beans:bean&gt; &lt;beans:bean id="myAccessDecisionManager" class="myAccessDecisionManager"&gt;&lt;/beans:bean&gt; &lt;beans:bean id="mySecurityMetadataSource"
class="cn.com.abel.test.service.security.MySecurityMetadataSource"&gt;
&lt;beans:constructor-arg&gt;
&lt;beans:ref bean="resourceService" /&gt;
&lt;/beans:constructor-arg&gt;
&lt;/beans:bean&gt; &lt;beans:bean id="encoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"&gt;&lt;/beans:bean&gt;

</beans:beans>

3、MyUsernamePasswordAuthenticationFilter.java

  1. package cn.com.abel.test.service.security;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.springframework.security.authentication.AuthenticationServiceException;
  5. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  6. import org.springframework.security.core.Authentication;
  7. import org.springframework.security.core.AuthenticationException;
  8. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
  9. public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
  10. @Override
  11. public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
  12. if (!request.getMethod().equals("POST")) {
  13. throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
  14. }
  15. String username = obtainUsername(request);
  16. String password = obtainPassword(request);
  17. if (username == null) {
  18. username = "";
  19. }
  20. if (password == null) {
  21. password = "";
  22. }
  23. username = username.trim();
  24. UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
  25. // Allow subclasses to set the "details" property
  26. setDetails(request, authRequest);
  27. //      //登录验证码,如需要开启把下面注释去掉则可
  28. //      String authCode = StringUtils.defaultString(request.getParameter("authCode"));
  29. //      if(!AdwImageCaptchaServlet.validateResponse(request, authCode)){
  30. //          throw new AuthenticationServiceException("validCode.auth.fail");
  31. //      }
  32. return this.getAuthenticationManager().authenticate(authRequest);
  33. }
  34. }
package cn.com.abel.test.service.security;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse; import org.springframework.security.authentication.AuthenticationServiceException;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

import org.springframework.security.core.Authentication;

import org.springframework.security.core.AuthenticationException;

import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
@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); if (username == null) {
username = "";
} if (password == null) {
password = "";
} username = username.trim(); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); // Allow subclasses to set the "details" property
setDetails(request, authRequest);

// //登录验证码,如需要开启把下面注释去掉则可

// String authCode = StringUtils.defaultString(request.getParameter("authCode"));

// if(!AdwImageCaptchaServlet.validateResponse(request, authCode)){

// throw new AuthenticationServiceException("validCode.auth.fail");

// }

	return this.getAuthenticationManager().authenticate(authRequest);
}

}

4、MySecurityFilter.java

  1. package cn.com.abel.test.service.security;
  2. import java.io.IOException;
  3. import javax.servlet.Filter;
  4. import javax.servlet.FilterChain;
  5. import javax.servlet.FilterConfig;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.ServletRequest;
  8. import javax.servlet.ServletResponse;
  9. import org.springframework.security.access.SecurityMetadataSource;
  10. import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
  11. import org.springframework.security.access.intercept.InterceptorStatusToken;
  12. import org.springframework.security.web.FilterInvocation;
  13. import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
  14. public class MySecurityFilter extends AbstractSecurityInterceptor implements Filter {
  15. //与applicationContext-security.xml里的myFilter的属性securityMetadataSource对应,
  16. //其他的两个组件,已经在AbstractSecurityInterceptor定义
  17. private FilterInvocationSecurityMetadataSource securityMetadataSource;
  18. @Override
  19. public SecurityMetadataSource obtainSecurityMetadataSource() {
  20. return this.securityMetadataSource;
  21. }
  22. public void doFilter(ServletRequest request, ServletResponse response,
  23. FilterChain chain) throws IOException, ServletException {
  24. FilterInvocation fi = new FilterInvocation(request, response, chain);
  25. invoke(fi);
  26. }
  27. private void invoke(FilterInvocation fi) throws IOException, ServletException {
  28. // object为FilterInvocation对象
  29. //1.获取请求资源的权限
  30. //执行Collection<ConfigAttribute> attributes = SecurityMetadataSource.getAttributes(object);
  31. //2.是否拥有权限
  32. //获取安全主体,可以强制转换为UserDetails的实例
  33. //1) UserDetails
  34. // Authentication authenticated = authenticateIfRequired();
  35. //this.accessDecisionManager.decide(authenticated, object, attributes);
  36. //用户拥有的权限
  37. //2) GrantedAuthority
  38. //Collection<GrantedAuthority> authenticated.getAuthorities()
  39. //System.out.println("用户发送请求! ");
  40. InterceptorStatusToken token = null;
  41. token = super.beforeInvocation(fi);
  42. try {
  43. fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
  44. } finally {
  45. super.afterInvocation(token, null);
  46. }
  47. }
  48. public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
  49. return securityMetadataSource;
  50. }
  51. public void setSecurityMetadataSource(FilterInvocationSecurityMetadataSource securityMetadataSource) {
  52. this.securityMetadataSource = securityMetadataSource;
  53. }
  54. public void init(FilterConfig arg0) throws ServletException {
  55. // TODO Auto-generated method stub
  56. }
  57. public void destroy() {
  58. // TODO Auto-generated method stub
  59. }
  60. @Override
  61. public Class<? extends Object> getSecureObjectClass() {
  62. //下面的MyAccessDecisionManager的supports方面必须放回true,否则会提醒类型错误
  63. return FilterInvocation.class;
  64. }
  65. }
package cn.com.abel.test.service.security;

import java.io.IOException;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse; import org.springframework.security.access.SecurityMetadataSource;

import org.springframework.security.access.intercept.AbstractSecurityInterceptor;

import org.springframework.security.access.intercept.InterceptorStatusToken;

import org.springframework.security.web.FilterInvocation;

import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; public class MySecurityFilter extends AbstractSecurityInterceptor implements Filter {

//与applicationContext-security.xml里的myFilter的属性securityMetadataSource对应

//其他的两个组件,已经在AbstractSecurityInterceptor定义

private FilterInvocationSecurityMetadataSource securityMetadataSource;
@Override
public SecurityMetadataSource obtainSecurityMetadataSource() {
return this.securityMetadataSource;
} public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
FilterInvocation fi = new FilterInvocation(request, response, chain);
invoke(fi);
} private void invoke(FilterInvocation fi) throws IOException, ServletException {
// object为FilterInvocation对象
//1.获取请求资源的权限
//执行Collection&lt;ConfigAttribute&gt; attributes = SecurityMetadataSource.getAttributes(object);
//2.是否拥有权限
//获取安全主体,可以强制转换为UserDetails的实例
//1) UserDetails
// Authentication authenticated = authenticateIfRequired();
//this.accessDecisionManager.decide(authenticated, object, attributes);
//用户拥有的权限
//2) GrantedAuthority
//Collection&lt;GrantedAuthority&gt; authenticated.getAuthorities()
//System.out.println("用户发送请求! ");
InterceptorStatusToken token = null; token = super.beforeInvocation(fi); try {
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
} finally {
super.afterInvocation(token, null);
}
} public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
return securityMetadataSource;
} public void setSecurityMetadataSource(FilterInvocationSecurityMetadataSource securityMetadataSource) {
this.securityMetadataSource = securityMetadataSource;
} public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
} public void destroy() {
// TODO Auto-generated method stub } @Override
public Class&lt;? extends Object&gt; getSecureObjectClass() {
//下面的MyAccessDecisionManager的supports方面必须放回true,否则会提醒类型错误
return FilterInvocation.class;
}

}

5、AdminUserDetailServiceImpl.java

  1. package cn.com.abel.test.service.security;
  2. import java.util.HashSet;
  3. import java.util.List;
  4. import java.util.Set;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.security.core.GrantedAuthority;
  7. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  8. import org.springframework.security.core.userdetails.UserDetails;
  9. import org.springframework.security.core.userdetails.UserDetailsService;
  10. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  11. import cn.com.abel.test.model.RoleModel;
  12. import cn.com.abel.test.model.MemberModel;
  13. import cn.com.abel.test.service.RoleService;
  14. import cn.com.abel.test.service.MemberService;
  15. public class AdminUserDetailServiceImpl implements UserDetailsService {
  16. @Autowired
  17. private MemberService memberService;
  18. @Autowired
  19. RoleService roleService;
  20. //登录验证
  21. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  22. MemberModel member = memberService.getUserDetailsByUserName(username);
  23. if(member==null){
  24. throw new UsernameNotFoundException("member "+username +" not found.");
  25. }
  26. Set<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(member);
  27. //封装成spring security的user
  28. User userdetail = new User(user.getUserName(), user.getPassword(),
  29. true, // 账号状态 0 表示停用 1表示启用
  30. true, true, true, grantedAuths // 用户的权限
  31. );
  32. return userdetail;
  33. }
  34. //取得用户的权限
  35. private Set<GrantedAuthority> obtionGrantedAuthorities(MemberModel member) {
  36. Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
  37. List<RoleModel> roles = roleService.getRoleByUser(member)<span style="font-family:Arial, Helvetica, sans-serif;">;</span>
  38. if(roles!=null){
  39. for(RoleModel role : roles) {
  40. authSet.add(new SimpleGrantedAuthority(role.getRoleCode().trim()));
  41. }
  42. }
  43. return authSet;
  44. }
  45. }
package cn.com.abel.test.service.security;

import java.util.HashSet;

import java.util.List;

import java.util.Set; 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.UserDetails;

import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.core.userdetails.UsernameNotFoundException; import cn.com.abel.test.model.RoleModel;

import cn.com.abel.test.model.MemberModel;

import cn.com.abel.test.service.RoleService;

import cn.com.abel.test.service.MemberService; public class AdminUserDetailServiceImpl implements UserDetailsService {

@Autowired

private MemberService memberService;

@Autowired

RoleService roleService;
//登录验证
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { MemberModel member = memberService.getUserDetailsByUserName(username); if(member==null){
throw new UsernameNotFoundException("member "+username +" not found.");
}
Set&lt;GrantedAuthority&gt; grantedAuths = obtionGrantedAuthorities(member); //封装成spring security的user
User userdetail = new User(user.getUserName(), user.getPassword(),
true, // 账号状态 0 表示停用 1表示启用
true, true, true, grantedAuths // 用户的权限
);
return userdetail;
} //取得用户的权限
private Set&lt;GrantedAuthority&gt; obtionGrantedAuthorities(MemberModel member) { Set&lt;GrantedAuthority&gt; authSet = new HashSet&lt;GrantedAuthority&gt;(); List&lt;RoleModel&gt; roles = roleService.getRoleByUser(member)&lt;span style="font-family:Arial, Helvetica, sans-serif;"&gt;;&lt;/span&gt;
if(roles!=null){
for(RoleModel role : roles) {
authSet.add(new SimpleGrantedAuthority(role.getRoleCode().trim()));
}
} return authSet;
}

}

6、MyAccessDecisionManager.java

  1. package cn.com.abel.test.service.security;
  2. import java.util.Collection;
  3. import java.util.Iterator;
  4. import org.springframework.security.access.AccessDecisionManager;
  5. import org.springframework.security.access.AccessDeniedException;
  6. import org.springframework.security.access.ConfigAttribute;
  7. import org.springframework.security.authentication.InsufficientAuthenticationException;
  8. import org.springframework.security.core.Authentication;
  9. import org.springframework.security.core.GrantedAuthority;
  10. public class MyAccessDecisionManager implements AccessDecisionManager {
  11. public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
  12. if(configAttributes == null) {
  13. return;
  14. }
  15. //所请求的资源拥有的权限(一个资源对多个权限)
  16. Iterator<ConfigAttribute> iterator = configAttributes.iterator();
  17. while(iterator.hasNext()) {
  18. ConfigAttribute configAttribute = iterator.next();
  19. //访问所请求资源所需要的权限
  20. String needPermission = configAttribute.getAttribute();
  21. System.out.println("needPermission is " + needPermission);
  22. //用户所拥有的权限authentication
  23. for(GrantedAuthority ga : authentication.getAuthorities()) {
  24. if(needPermission.equals(ga.getAuthority())) {
  25. return;
  26. }
  27. }
  28. }
  29. //没有权限让我们去捕捉
  30. throw new AccessDeniedException(" 没有权限访问!");
  31. }
  32. public boolean supports(ConfigAttribute attribute) {
  33. // TODO Auto-generated method stub
  34. return true;
  35. }
  36. public boolean supports(Class<?> clazz) {
  37. // TODO Auto-generated method stub
  38. return true;
  39. }
  40. }
package cn.com.abel.test.service.security;

import java.util.Collection;

import java.util.Iterator; import org.springframework.security.access.AccessDecisionManager;

import org.springframework.security.access.AccessDeniedException;

import org.springframework.security.access.ConfigAttribute;

import org.springframework.security.authentication.InsufficientAuthenticationException;

import org.springframework.security.core.Authentication;

import org.springframework.security.core.GrantedAuthority; public class MyAccessDecisionManager implements AccessDecisionManager {
public void decide(Authentication authentication, Object object, Collection&lt;ConfigAttribute&gt; configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
if(configAttributes == null) {
return;
}
//所请求的资源拥有的权限(一个资源对多个权限)
Iterator&lt;ConfigAttribute&gt; iterator = configAttributes.iterator();
while(iterator.hasNext()) {
ConfigAttribute configAttribute = iterator.next();
//访问所请求资源所需要的权限
String needPermission = configAttribute.getAttribute();
System.out.println("needPermission is " + needPermission);
//用户所拥有的权限authentication
for(GrantedAuthority ga : authentication.getAuthorities()) {
if(needPermission.equals(ga.getAuthority())) {
return;
}
}
}
//没有权限让我们去捕捉
throw new AccessDeniedException(" 没有权限访问!");
} public boolean supports(ConfigAttribute attribute) {
// TODO Auto-generated method stub
return true;
} public boolean supports(Class&lt;?&gt; clazz) {
// TODO Auto-generated method stub
return true;
}

}

7、MySecurityMetadataSource.java

  1. package cn.com.abel.test.service.security;
  2. import java.util.ArrayList;
  3. import java.util.Collection;
  4. import java.util.HashSet;
  5. import java.util.Iterator;
  6. import java.util.List;
  7. import java.util.Map;
  8. import java.util.Map.Entry;
  9. import java.util.TreeMap;
  10. import java.util.concurrent.ConcurrentHashMap;
  11. import javax.servlet.http.HttpServletRequest;
  12. import org.apache.commons.lang.StringUtils;
  13. import org.springframework.beans.factory.InitializingBean;
  14. import org.springframework.security.access.ConfigAttribute;
  15. import org.springframework.security.access.SecurityConfig;
  16. import org.springframework.security.web.FilterInvocation;
  17. import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
  18. import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
  19. import org.springframework.security.web.util.matcher.RequestMatcher;
  20. import cn.com.abel.test.model.RoleModel;
  21. import cn.com.abel.test.service.ResourceService;
  22. public class MySecurityMetadataSource  implements FilterInvocationSecurityMetadataSource,InitializingBean {
  23. private static final String AUTH_NO_ROLE =" __AUTH_NO_ROLE__";
  24. private ResourceService resourceService;
  25. public MySecurityMetadataSource(ResourceService resourceService) {
  26. this.resourceService = resourceService;
  27. }
  28. private static Map<String, Collection<ConfigAttribute>> resourceMap = null;
  29. public Collection<ConfigAttribute> getAllConfigAttributes() {
  30. return null;
  31. }
  32. public boolean supports(Class<?> clazz) {
  33. return true;
  34. }
  35. private void loadResourceDefine() {
  36. if(resourceMap == null) {
  37. resourceMap = new ConcurrentHashMap<String, Collection<ConfigAttribute>>();
  38. }else{
  39. resourceMap.clear();
  40. }
  41. Map<String,List<RoleModel>> resourceRoleMap = resourceService.getAllResourceRole();
  42. for (Entry<String,List<RoleModel>> entry : resourceRoleMap.entrySet()) {
  43. String url = entry.getKey();
  44. List<RoleModel> values = entry.getValue();
  45. Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
  46. for(RoleModel secRoleModel : values){
  47. ConfigAttribute configAttribute = new SecurityConfig(StringUtils.defaultString(secRoleModel.getRoleCode(),AUTH_NO_ROLE));
  48. configAttributes.add(configAttribute);
  49. }
  50. resourceMap.put(url, configAttributes);
  51. }
  52. }
  53. public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
  54. HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
  55. TreeMap<String, Collection<ConfigAttribute>> attrMap = new TreeMap<String, Collection<ConfigAttribute>>(resourceMap);
  56. Iterator<String> ite = attrMap.keySet().iterator();
  57. RequestMatcher urlMatcher = null;
  58. Collection<ConfigAttribute> attrSet = new HashSet<ConfigAttribute>();
  59. //match all of /admin/**  a/b/**
  60. while (ite.hasNext()) {
  61. String resURL = ite.next();
  62. urlMatcher = new AntPathRequestMatcher(resURL);
  63. if (urlMatcher.matches(request)||StringUtils.equals(request.getRequestURI(),resURL)) {
  64. attrSet.addAll(attrMap.get(resURL));
  65. }
  66. }
  67. if(!attrSet.isEmpty()){
  68. return attrSet;
  69. }
  70. return null;
  71. }
  72. @Override
  73. public void afterPropertiesSet() throws Exception {
  74. loadResourceDefine() ;
  75. }
  76. }
package cn.com.abel.test.service.security;

import java.util.ArrayList;

import java.util.Collection;

import java.util.HashSet;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import java.util.TreeMap;

import java.util.concurrent.ConcurrentHashMap; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils;

import org.springframework.beans.factory.InitializingBean;

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 org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import org.springframework.security.web.util.matcher.RequestMatcher; import cn.com.abel.test.model.RoleModel;

import cn.com.abel.test.service.ResourceService; public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource,InitializingBean {
private static final String AUTH_NO_ROLE =" __AUTH_NO_ROLE__";

private ResourceService resourceService;

public MySecurityMetadataSource(ResourceService resourceService) {
this.resourceService = resourceService;
} private static Map&lt;String, Collection&lt;ConfigAttribute&gt;&gt; resourceMap = null; public Collection&lt;ConfigAttribute&gt; getAllConfigAttributes() {
return null;
} public boolean supports(Class&lt;?&gt; clazz) {
return true;
}
private void loadResourceDefine() {
if(resourceMap == null) {
resourceMap = new ConcurrentHashMap&lt;String, Collection&lt;ConfigAttribute&gt;&gt;();
}else{
resourceMap.clear();
} Map&lt;String,List&lt;RoleModel&gt;&gt; resourceRoleMap = resourceService.getAllResourceRole(); for (Entry&lt;String,List&lt;RoleModel&gt;&gt; entry : resourceRoleMap.entrySet()) {
String url = entry.getKey();
List&lt;RoleModel&gt; values = entry.getValue(); Collection&lt;ConfigAttribute&gt; configAttributes = new ArrayList&lt;ConfigAttribute&gt;();
for(RoleModel secRoleModel : values){
ConfigAttribute configAttribute = new SecurityConfig(StringUtils.defaultString(secRoleModel.getRoleCode(),AUTH_NO_ROLE));
configAttributes.add(configAttribute);
}
resourceMap.put(url, configAttributes);
}
}
public Collection&lt;ConfigAttribute&gt; getAttributes(Object object) throws IllegalArgumentException { HttpServletRequest request = ((FilterInvocation) object).getHttpRequest(); TreeMap&lt;String, Collection&lt;ConfigAttribute&gt;&gt; attrMap = new TreeMap&lt;String, Collection&lt;ConfigAttribute&gt;&gt;(resourceMap); Iterator&lt;String&gt; ite = attrMap.keySet().iterator(); RequestMatcher urlMatcher = null; Collection&lt;ConfigAttribute&gt; attrSet = new HashSet&lt;ConfigAttribute&gt;();
//match all of /admin/** a/b/**
while (ite.hasNext()) { String resURL = ite.next();
urlMatcher = new AntPathRequestMatcher(resURL); if (urlMatcher.matches(request)||StringUtils.equals(request.getRequestURI(),resURL)) {
attrSet.addAll(attrMap.get(resURL));
}
} if(!attrSet.isEmpty()){
return attrSet;
}
return null;
} @Override
public void afterPropertiesSet() throws Exception {
loadResourceDefine() ;
}

}

8、ResourceService.java

此类是为从数据库获取系统中的资源所属的角色,根据自己的数据表自行编写。

  1. package cn.com.abel.test.service;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.HashSet;
  5. import java.util.List;
  6. import java.util.Map;
  7. import org.apache.commons.collections.CollectionUtils;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Service;
  10. import cn.com.abel.test.mapper.ResourceModelMapper;
  11. import cn.com.abel.test.mapper.RoleModelMapper;
  12. import cn.com.abel.test.mapper.RoleResourcetModelMapper;
  13. import cn.com.abel.test.model.ResourceModel;
  14. import cn.com.abel.test.model.ResourceModelCriteria;
  15. import cn.com.abel.test.model.RoleModel;
  16. import cn.com.abel.test.model.RoleModelCriteria;
  17. import cn.com.abel.test.model.RoleResourcetModel;
  18. import cn.com.abel.test.model.RoleResourcetModelCriteria;
  19. @Service
  20. public class ResourceService {
  21. @Autowired
  22. ResourceModelMapper resourceModelMapper;
  23. @Autowired
  24. RoleModelMapper roleMapper;
  25. @Autowired
  26. RoleResourcetModelMapper  roleResMapper;
  27. /**
  28. * 获取各个资源(url)对应的角色
  29. * @return
  30. */
  31. public Map<String,List<RoleModel>> getAllResourceRole(){
  32. Map<String,List<RoleModel>> resultMap = new HashMap<String,List<RoleModel>>();
  33. ResourceModelCriteria secResourceModelExample = new ResourceModelCriteria();
  34. List<ResourceModel> resourceList = resourceModelMapper.selectByExample(secResourceModelExample);
  35. if(CollectionUtils.isNotEmpty(resourceList)){
  36. for(ResourceModel secResourceModel : resourceList){
  37. RoleModelCriteria roleCriteria = new RoleModelCriteria();
  38. roleCriteria.createCriteria().andIdIn(getRoleIdsByResourceId(secResourceModel.getId()));
  39. List<RoleModel> roleList = roleMapper.selectByExample(roleCriteria);
  40. resultMap.put(secResourceModel.getValue(), roleList);
  41. }
  42. }
  43. return resultMap;
  44. }
  45. public List<Integer> getRoleIdsByResourceId(Integer resourceId){
  46. List<Integer> roleIds = new ArrayList<Integer>();
  47. RoleResourcetModelCriteria criteria = new RoleResourcetModelCriteria();
  48. criteria.createCriteria().andResourceIdEqualTo(resourceId);
  49. List<RoleResourcetModel> list = roleResMapper.selectByExample(criteria);
  50. if(CollectionUtils.isNotEmpty(list)){
  51. for(RoleResourcetModel model : list){
  52. roleIds.add(model.getRoleId());
  53. }
  54. }
  55. HashSet<Integer> h  =   new  HashSet<Integer>(roleIds);
  56. roleIds.clear();
  57. roleIds.addAll(h);
  58. return roleIds;
  59. }
  60. }
package cn.com.abel.test.service;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.HashSet;

import java.util.List;

import java.util.Map; import org.apache.commons.collections.CollectionUtils;

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

import org.springframework.stereotype.Service; import cn.com.abel.test.mapper.ResourceModelMapper;

import cn.com.abel.test.mapper.RoleModelMapper;

import cn.com.abel.test.mapper.RoleResourcetModelMapper;

import cn.com.abel.test.model.ResourceModel;

import cn.com.abel.test.model.ResourceModelCriteria;

import cn.com.abel.test.model.RoleModel;

import cn.com.abel.test.model.RoleModelCriteria;

import cn.com.abel.test.model.RoleResourcetModel;

import cn.com.abel.test.model.RoleResourcetModelCriteria; @Service

public class ResourceService {
@Autowired
ResourceModelMapper resourceModelMapper; @Autowired
RoleModelMapper roleMapper; @Autowired
RoleResourcetModelMapper roleResMapper; /**
* 获取各个资源(url)对应的角色
* @return
*/
public Map&lt;String,List&lt;RoleModel&gt;&gt; getAllResourceRole(){ Map&lt;String,List&lt;RoleModel&gt;&gt; resultMap = new HashMap&lt;String,List&lt;RoleModel&gt;&gt;(); ResourceModelCriteria secResourceModelExample = new ResourceModelCriteria();
List&lt;ResourceModel&gt; resourceList = resourceModelMapper.selectByExample(secResourceModelExample); if(CollectionUtils.isNotEmpty(resourceList)){
for(ResourceModel secResourceModel : resourceList){
RoleModelCriteria roleCriteria = new RoleModelCriteria();
roleCriteria.createCriteria().andIdIn(getRoleIdsByResourceId(secResourceModel.getId()));
List&lt;RoleModel&gt; roleList = roleMapper.selectByExample(roleCriteria);
resultMap.put(secResourceModel.getValue(), roleList); }
} return resultMap;
} public List&lt;Integer&gt; getRoleIdsByResourceId(Integer resourceId){
List&lt;Integer&gt; roleIds = new ArrayList&lt;Integer&gt;(); RoleResourcetModelCriteria criteria = new RoleResourcetModelCriteria();
criteria.createCriteria().andResourceIdEqualTo(resourceId);
List&lt;RoleResourcetModel&gt; list = roleResMapper.selectByExample(criteria);
if(CollectionUtils.isNotEmpty(list)){
for(RoleResourcetModel model : list){
roleIds.add(model.getRoleId());
}
} HashSet&lt;Integer&gt; h = new HashSet&lt;Integer&gt;(roleIds);
roleIds.clear();
roleIds.addAll(h);
return roleIds;
}

}

最后附上数据表的SQL:

  1. CREATE TABLE `auth_resource` (
  2. `id` INT(11) NOT NULL AUTO_INCREMENT,
  3. `name` VARCHAR(100) NULL DEFAULT NULL COMMENT '资源名称',
  4. `value` VARCHAR(100) NULL DEFAULT NULL COMMENT '资源值',
  5. `summary` VARCHAR(1000) NULL DEFAULT NULL COMMENT '资源描述',
  6. `updated_time` DATETIME NULL DEFAULT NULL,
  7. `updated_user` VARCHAR(100) NULL DEFAULT NULL,
  8. PRIMARY KEY (`id`)
  9. )
  10. COMMENT='资源访问表'
  11. COLLATE='utf8_general_ci'
  12. ENGINE=InnoDB;
  13. CREATE TABLE `auth_role` (
  14. `id` INT(11) NOT NULL AUTO_INCREMENT,
  15. `role_name` VARCHAR(100) NULL DEFAULT NULL COMMENT '角色名称',
  16. `role_code` VARCHAR(100) NULL DEFAULT NULL COMMENT '角色代码',
  17. `updated_time` DATETIME NULL DEFAULT NULL,
  18. `updated_user` VARCHAR(100) NULL DEFAULT NULL,
  19. PRIMARY KEY (`id`)
  20. )
  21. COMMENT='角色表'
  22. COLLATE='utf8_general_ci'
  23. ENGINE=InnoDB;
  24. CREATE TABLE `role_resource` (
  25. `id` INT(11) NOT NULL AUTO_INCREMENT,
  26. `role_id` INT(11) NOT NULL,
  27. `resource_id` INT(11) NOT NULL,
  28. PRIMARY KEY (`id`),
  29. UNIQUE INDEX `role_id_resource_id` (`role_id`, `resource_id`)
  30. )
  31. COMMENT='资源角色关联表'
  32. COLLATE='utf8_general_ci'
  33. ENGINE=InnoDB;
  34. CREATE TABLE `member` (
  35. `id` INT(11) NOT NULL AUTO_INCREMENT,
  36. `user_name` VARCHAR(100) NULL DEFAULT NULL,
  37. `nick` VARCHAR(100) NULL DEFAULT NULL,
  38. `password` VARCHAR(100) NULL DEFAULT NULL,
  39. `sex` INT(11) NULL DEFAULT NULL,
  40. `birthday` DATE NULL DEFAULT NULL,
  41. `mobile` VARCHAR(50) NULL DEFAULT NULL,
  42. `email` VARCHAR(50) NULL DEFAULT NULL,
  43. `address` VARCHAR(512) NULL DEFAULT NULL,
  44. `regip` VARCHAR(100) NULL DEFAULT NULL,
  45. `created_time` DATETIME NULL DEFAULT NULL,
  46. PRIMARY KEY (`id`)
  47. )
  48. COMMENT='用户表'
  49. COLLATE='utf8_general_ci'
  50. ENGINE=InnoDB
  51. AUTO_INCREMENT=2;
  52. CREATE TABLE `member_role` (
  53. `id` INT(11) NOT NULL AUTO_INCREMENT,
  54. `member_id` INT(11) NOT NULL,
  55. `role_id` INT(11) NOT NULL,
  56. PRIMARY KEY (`id`),
  57. UNIQUE INDEX `member_id_role_id` (`member_id`, `role_id`)
  58. )
  59. COMMENT='用户角色关联表'
  60. COLLATE='utf8_general_ci'
  61. ENGINE=InnoDB;
CREATE TABLE `auth_resource` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NULL DEFAULT NULL COMMENT '资源名称',
`value` VARCHAR(100) NULL DEFAULT NULL COMMENT '资源值',
`summary` VARCHAR(1000) NULL DEFAULT NULL COMMENT '资源描述',
`updated_time` DATETIME NULL DEFAULT NULL,
`updated_user` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COMMENT='资源访问表'
COLLATE='utf8_general_ci'
ENGINE=InnoDB; CREATE TABLE auth_role (

id INT(11) NOT NULL AUTO_INCREMENT,

role_name VARCHAR(100) NULL DEFAULT NULL COMMENT '角色名称',

role_code VARCHAR(100) NULL DEFAULT NULL COMMENT '角色代码',

updated_time DATETIME NULL DEFAULT NULL,

updated_user VARCHAR(100) NULL DEFAULT NULL,

PRIMARY KEY (id)

)

COMMENT='角色表'

COLLATE='utf8_general_ci'

ENGINE=InnoDB; CREATE TABLE role_resource (

id INT(11) NOT NULL AUTO_INCREMENT,

role_id INT(11) NOT NULL,

resource_id INT(11) NOT NULL,

PRIMARY KEY (id),

UNIQUE INDEX role_id_resource_id (role_id, resource_id)

)

COMMENT='资源角色关联表'

COLLATE='utf8_general_ci'

ENGINE=InnoDB; CREATE TABLE member (

id INT(11) NOT NULL AUTO_INCREMENT,

user_name VARCHAR(100) NULL DEFAULT NULL,

nick VARCHAR(100) NULL DEFAULT NULL,

password VARCHAR(100) NULL DEFAULT NULL,

sex INT(11) NULL DEFAULT NULL,

birthday DATE NULL DEFAULT NULL,

mobile VARCHAR(50) NULL DEFAULT NULL,

email VARCHAR(50) NULL DEFAULT NULL,

address VARCHAR(512) NULL DEFAULT NULL,

regip VARCHAR(100) NULL DEFAULT NULL,

created_time DATETIME NULL DEFAULT NULL,

PRIMARY KEY (id)

)

COMMENT='用户表'

COLLATE='utf8_general_ci'

ENGINE=InnoDB

AUTO_INCREMENT=2; CREATE TABLE member_role (

id INT(11) NOT NULL AUTO_INCREMENT,

member_id INT(11) NOT NULL,

role_id INT(11) NOT NULL,

PRIMARY KEY (id),

UNIQUE INDEX member_id_role_id (member_id, role_id)

)

COMMENT='用户角色关联表'

COLLATE='utf8_general_ci'

ENGINE=InnoDB;

完整代码下载(包含数据库):http://download.csdn.net/download/rongku/9931455

spring security 登录、权限管理配置的更多相关文章

  1. 使用Spring Security实现权限管理

    使用Spring Security实现权限管理 1.技术目标 了解并创建Security框架所需数据表 为项目添加Spring Security框架 掌握Security框架配置 应用Security ...

  2. Spring Security 之Session管理配置

    废话不多说,直接上代码.示例如下: 1.   新建Maven项目  session 2.   pom.xml <project xmlns="http://maven.apache.o ...

  3. springBoot整合spring security实现权限管理(单体应用版)--筑基初期

    写在前面 在前面的学习当中,我们对spring security有了一个小小的认识,接下来我们整合目前的主流框架springBoot,实现权限的管理. 在这之前,假定你已经了解了基于资源的权限管理模型 ...

  4. (39.1) Spring Boot Shiro权限管理【从零开始学Spring Boot】

    (本节提供源代码,在最下面可以下载)距上一个章节过了二个星期了,最近时间也是比较紧,一直没有时间可以写博客,今天难得有点时间,就说说Spring Boot如何集成Shiro吧.这个章节会比较复杂,牵涉 ...

  5. Spring Boot Shiro 权限管理

    Spring Boot Shiro 权限管理 标签: springshiro 2016-01-14 23:44 94587人阅读 评论(60) 收藏 举报 .embody{ padding:10px ...

  6. spring boot rest 接口集成 spring security(1) - 最简配置

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  7. SpringBoot 优雅配置跨域多种方式及Spring Security跨域访问配置的坑

    前言 最近在做项目的时候,基于前后端分离的权限管理系统,后台使用 Spring Security 作为权限控制管理, 然后在前端接口访问时候涉及到跨域,但我怎么配置跨域也没有生效,这里有一个坑,在使用 ...

  8. Spring Security控制权限

    Spring Security控制权限 1,配置过滤器 为了在项目中使用Spring Security控制权限,首先要在web.xml中配置过滤器,这样我们就可以控制对这个项目的每个请求了. < ...

  9. Spring Boot中使用 Spring Security 构建权限系统

    Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下文中配置的Bean,为应用系统提供声明式的安全 ...

  10. Spring Security 登录校验 源码解析

    传统情况下,在过滤器中做权限验证,Spring Secuirty也是在Filter中进行权限验证. 创建并注册过滤器 package com.awizdata.edubank.config; impo ...

随机推荐

  1. 洛谷 P1901 发射站

    题目描述 某地有 N 个能量发射站排成一行,每个发射站 i 都有不相同的高度 Hi,并能向两边(当 然两端的只能向一边)同时发射能量值为 Vi 的能量,并且发出的能量只被两边最近的且比 它高的发射站接 ...

  2. 机器学习之 PCA (二)

    参考  http://www.cnblogs.com/frombeijingwithlove/p/5931872.html

  3. gendiff - 致力于创建无错的 diff 文件的工具

    SYNOPSIS gendiff <directory> <diff-extension> DESCRIPTION gendiff 是一个简单的脚本,目标是根据单一的目录生成一 ...

  4. Java加腾讯云实现短信验证码功能

    一.概要 现如今在日常工作和生活中短信验证码对于我们来说是非常熟悉的,比较常见的注册账号或者交易支付时候,手机会收到一个短信验证码,我们可以通过验证码来有效验证身份,避免一些信息被盗. 验证身份 目前 ...

  5. Java递归获取部门树 返回jstree数据

    @GetMapping("/getDept")@ResponseBodypublic Tree<DeptDO> getDept(String deptId){ Tree ...

  6. 第三届上海市大学生网络安全大赛wp&学习

    wp 0x00 p200 先分析了程序关键的数据结构 分析程序逻辑,在free堆块的时候没有清空指针,造成悬挂指针,并且程序中给了system('/bin/sh'),可以利用uaf 脚本如下: 1.先 ...

  7. uaf-湖湘杯2016game_学习

    0x00 分析程序 根据分析,我们可以得到以下重要数据结构 0x01 发现漏洞 1.在武器使用次数耗光后,程序会把存储该武器的堆块free,在free的时候没有清空指针,造成悬挂指针 2.commen ...

  8. Web开发面临的挑战主要有哪些?

    摘要:要成为一名高效的Web开发者,这需要我们做很多工作,来提高我们的工作方式,以及改善我们的劳动成果.而在开发中难免会遇到一些困难,从前端到后端. 导读:要成为一名高效的Web开发者,这需要我们做很 ...

  9. laravel如何利用数据库的形式发送通知

    具体实现需要分几步: 1.修改驱动为database; 2.创建database的queue表 3.创建任务sendMessage 4.创建发送逻辑dispatch 5.启动队列 接下来我们进行实操: ...

  10. A Fast and Easy to Use AES Library

    http://www.codeproject.com/Articles/57478/A-Fast-and-Easy-to-Use-AES-Library Introduction EfAesLib i ...