spring security 4验证成功后为什么不能跳转到方法

Spring Security 问题:如何不通过认证可以使用系统部分功能 - 开源中国社区
当前访客身份:游客 [
当前位置:
& & &&本人现在想实现该功能,系统采用spring security验证来登陆系统,现在系统中有部分功能想对外开放且不输入密码,只需要账号来访问该功能。
& & spring相关包:
所想方法有:1.直接放开不过滤掉某个 方法底下的内容。如:
&intercept-url pattern=&/sendUtil/autoSettleUtil& filters=&none& /&
但是该方法有个缺点是如果后台访问不放开的内容时,还是会跳转到登陆界面。
2.修改spring security配置文件。但是配置文件改动时,发现理解的不透彻,方法有点问题。如下是我的配置文件代码:
&global-method-security secured-annotations=&enabled&&
&!-- AspectJ pointcut expression that locates our &post& method and applies security that way
&protect-pointcut expression=&execution(* bigbank.*Service.post*(..))& access=&ROLE_TELLER&/&
&/global-method-security&
&http auto-config=&true&&
&intercept-url pattern=&/& filters=&none&/&
&intercept-url pattern=&/login.jsp*& filters=&none&/&
&intercept-url pattern=&/common/**& filters=&none& /&
&intercept-url pattern=&/common/css/**& filters=&none& /&
&intercept-url pattern=&/common/css/login/**& filters=&none& /&
&intercept-url pattern=&/widgets/**& filters=&none& /&
&intercept-url pattern=&/requestCombo& filters=&none& /&
下载操作手册时,不需要登录 该方法是Servlet方法--&
&intercept-url pattern=&/download/downloadFile& filters=&none& /&
&!-- 增加 定时发送邮件功能
该方法是Servlet方法 --&
&intercept-url pattern=&/sendUtil/autoSettleUtil& filters=&none& /&
&intercept-url pattern=&/**& access=&ROLE_USER&/&
&form-login login-page=&/login.jsp& default-target-url=&/& authentication-failure-url=&/login.jsp?login_error=true& /&
&logout invalidate-session=&true&
logout-url=&/j_spring_security_logout& logout-success-url=&/&/&
Uncomment to enable X509 client authentication support
&!-- All of this is unnecessary if auto-config=&true&
&form-login /&
&anonymous /&
&http-basic /&
&logout /&
&remember-me /& --&
&!-- Uncomment to limit the number of sessions a user can have
&concurrent-session-control max-sessions=&1& exception-if-maximum-exceeded=&true&/&
Usernames/Passwords are
dianne/emu
scott/wombat
peter/opal
&authentication-provider user-service-ref=&userDetailsService& &
&password-encoder ref=&customPasswordEncoder&/&
&/authentication-provider&
&beans:bean id=&userDetailsService& class=&org.springframework.security.userdetails.jdbc.JdbcDaoImpl&&
&beans:property name=&usersByUsernameQuery& value=&SELECT agentid ,password,'1' as validstatus FROM pwd_stauserlogin WHERE
agentid = ?&&&/beans:property&
&beans:property name=&authoritiesByUsernameQuery& value=&SELECT agentid ,'ROLE_USER' FROM pwd_stauserlogin WHERE
agentid = ?&&&/beans:property&
&beans:property name=&groupAuthoritiesByUsernameQuery& value=&SELECT 0,'ROLE_USER','ROLE_USER' FROM pwd_stauserlogin WHERE
agentid = ?&&&/beans:property&
&beans:property name=&usersByUsernameQuery& value=&SELECT usercode,password,validstatus FROM saa_user WHERE usercode = ?&&&/beans:property&
&beans:property name=&authoritiesByUsernameQuery& value=&SELECT usercode,'ROLE_USER' FROM saa_user WHERE usercode = ?&&&/beans:property&
&beans:property name=&groupAuthoritiesByUsernameQuery& value=&SELECT 0,'ROLE_USER','ROLE_USER' FROM saa_user WHERE usercode = ?&&&/beans:property&
&/beans:bean&
&beans:bean id=&customPasswordEncoder& class=&com.sinosoft.mon.MD5CapitalPasswordEncoder&/&
&!-- 用于自定义异常信息 --&
&beans:bean id=&messageSource& class=&org.springframework.context.support.ReloadableResourceBundleMessageSource&&
&beans:property name=&basename& value=&classpath:i18n/security/messages&/&
&/beans:bean&
&beans:bean id=&loginFilter& class=&com.sinosoft.app.security.LoginFilter&&
&custom-filter after=&LOGOUT_FILTER& /&
&custom-filter after=&FILTER_SECURITY_INTERCEPTOR& /&
&/beans:bean&
--& 最底下注释内容是本人想实现的方法,但是个人把握不准,未能实现。
请大家能个建议,如果有相关例子是更好,毕竟现在有点小急,谢谢大家了!
个人邮箱:
共有3个答案
<span class="a_vote_num" id="a_vote_num_
授权模块 自己重写
--- 共有 1 条评论 ---
就是这个地方,有点问题,授权模块的经常被绕晕,没学习到精华
(4年前)&nbsp&
<span class="a_vote_num" id="a_vote_num_
直接弄个用户,页面加个游客登录按钮,点击按钮发送你预设的用户名密码
然后按正常用户处理
<span class="a_vote_num" id="a_vote_num_
业务问题,不用改系统逻辑
更多开发者职位上
有什么技术问题吗?
漫画三毛的其它问题
类似的话题在线等。。关于spring-security框架登录的问题。。。-java-电脑编程网在线等。。关于spring-security框架登录的问题。。。作者:ypchengmsdn 和相关&&Java code
applicationContext-security.xml配置:
&?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-2.5.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.xsd&&
&http auto-config=&true&&
&intercept-url pattern=&/login.& filters=&none&/&
&intercept-url pattern=&/images/**& filters=&none&/&
&intercept-url pattern=&/include/**& filters=&none&/&
&intercept-url pattern=&/**& =&ROLE_USER& /&
&concurrent-session-control max-sessions=&1&/&
&form-login
login-page=&/login.&
authentication-failure-url=&/login.jsp?error=true&
default-target-url=&/&/&
&authentication-provider user-service-ref=&userDetailHibernateService&&
&/authentication-provider&
&/beans:beans&
login页面:
&form id=&form1& name=&form1& method=&post& action=&${pageContext.request.contextPath}/j_spring_security_check&&
&table width=&100%& border=&0& align=&center& cellpadding=&0&
cellspacing=&0& style=&margin-top: 20&&
&td width=&48& height=&40&&
&img src=&images/name_07.jpg& width=&45& height=&17& /&
&td colspan=&2&&
&input name=&j_username& type=&text& id=&j_username& value=&${sessionScope['SPRING_SECURITY_LAST_USERNAME']}&
size=&10& style=&background: #D9E6E4; height: 15 border: 1px #7CB0C7& /&
&td height=&40&&
&img src=&images/pass_10.jpg& width=&45& height=&15& /&
&td colspan=&2&&
&input name=&j_password& type=&password& id=&j_password& size=&10&
style=&background: #D9E6E4; height: 15 border: 1px #7CB0C7& /&
&td height=&70& colspan=&2&&
&img src=&images/enter_07.jpg& width=&88&
height=&51& border=&0& onclick=&form1.submit();&/&
&/form&
web.xml 配置:
&filter-name&springSecurityFilterChain&/filter-name&
&filter-class&org.springframework.web.filter.DelegatingFilterProxy&/filter-class&
&filter-mapping&
&filter-name&springSecurityFilterChain&/filter-name&
&url-pattern&/*&/url-pattern&
&/filter-mapping&
访问登录页面后,提示403错误:
HTTP Status 403 - Access is denied
但url已经跳转到 登录成功后的index.jsp页面了??
hibernate 也发出了 查询语句,说没有访问权限,问高手怎么解决???
------回答---------------其他回答(48分)---------/oa/springsecurity/html/index.html看看这里能不能找到你的答案
------其他回答(2分)---------applicationContext-security.xml配置没全啊,少了链接和角色的配置等,看楼上给的链接------回答---------------其他回答(48分)---------
/oa/springsecurity/html/index.html看看这里能不能找到你的答案
------其他回答(2分)---------applicationContext-security.xml配置没全啊,少了链接和角色的配置等,看楼上给的链接相关资料:|||||||在线等。。关于spring-security框架登录的问题。。。来源网络,如有侵权请告知,即处理!编程Tags:                &                    Spring Security集成Cas后页面跳转有关问题 - 开源软件当前位置:& &&&Spring Security集成Cas后页面跳转有关问题Spring Security集成Cas后页面跳转有关问题&&网友分享于:&&浏览:211次Spring Security集成Cas后页面跳转问题
问题描述:在集成cas后,如果在A应用里面直接调用B应用的某个页面,第一次点击的时候总是会跳转到B应用设置的默认页面,然后再点击的时候,才能跳转到正确的页面。后来通过查看源码,发现类:org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler
protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
if (isAlwaysUseDefaultTargetUrl()) {
return defaultTargetU
// Check for the parameter and use that if available
String targetUrl = request.getParameter(targetUrlParameter);
这个方法首先会判断是否设置了一直访问默认页面,如果false,则先获取request里面是否存在spring-security-redirect的参数,这个地址就是真正要跳转的URL; &!-- cas 认证成功控制器 --&
&beans:bean id="authenticationSuccessHandler"
class="org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler"&
&beans:property name="alwaysUseDefaultTargetUrl" value="false" /&
&beans:property name="defaultTargetUrl" value="/index.htm" /&
&/beans:bean&
这个配置改好后,接下这是怎么把spring-security-redirect带到url后面了,再看这个类CasAuthenticationEntryPoint类:org.springframework.security.cas.web.CasAuthenticationEntryPoint
public final void commence(final HttpServletRequest servletRequest, final HttpServletResponse response,
final AuthenticationException authenticationException) throws IOException, ServletException {
final String urlEncodedService = createServiceUrl(servletRequest, response);
final String redirectUrl = createRedirectUrl(urlEncodedService);
preCommence(servletRequest, response);
response.sendRedirect(redirectUrl);
protected String createServiceUrl(final HttpServletRequest request, final HttpServletResponse response) {
return CommonUtils.constructServiceUrl(null, response, this.serviceProperties.getService(), null,
this.serviceProperties.getArtifactParameter(), this.encodeServiceUrlWithSessionId);
这是验证未登录后,构建跳转的页面和参数(也就是登录页面)的处理方法,那在这里可以写一个类继承CasAuthenticationEntryPoint,重写createServiceUrl方法,spring-security-redirect的参数拼到redirectUrl后面,并且将当前请求url获取到;自定义类:CasAuthenticationRedirect
public class CasAuthenticationRedirect extends CasAuthenticationEntryPoint{
private String serviceUrlBak=
protected String createServiceUrl(final HttpServletRequest request, final HttpServletResponse response) {
if(serviceUrlBak==null)
serviceUrlBak=getServiceProperties().getService();
if(serviceUrlBak!=null){
String ctx=request.getContextPath();
String queryString=request.getQueryString();
String requestURI=request.getRequestURI();
requestURI=requestURI.substring(requestURI.indexOf(ctx)+ctx.length(),requestURI.length());
String serviceUrl="";
if(!requestURI.equals("/") && requestURI.length()&0){
serviceUrl="?"+AbstractAuthenticationTargetUrlRequestHandler.DEFAULT_TARGET_PARAMETER;
serviceUrl+="="+requestURI;
if(StringUtils.isNotBlank(queryString)){
serviceUrl+="?"+queryS
getServiceProperties().setService(serviceUrlBak+serviceUrl);
return super.createServiceUrl(request, response);
最后再将配置改一下:&beans:bean id="casEntryPoint" class="net.assertion.CasAuthenticationRedirect"&
&/beans:bean&这样就OK了,&& 这是目前找到最简单的解决方法了,不过,感觉既然spring提供了spring-security-redirect这个参数,应该会有相应的配置可以实现这个功能吧,哎...,主要是英文文档看不懂......
12345678910
12345678910
12345678910 上一篇:下一篇:文章评论相关解决方案 12345678910 Copyright & &&版权所有spring security验证成功后为什么不能跳转到方法_百度知道随笔 - 1202&
文章 - 45&评论 - 185&trackbacks - 0
httpSecurity
& &类似于spring security的xml配置文件命名空间配置中的&http&元素。它允许对特定的http请求基于安全考虑进行配置。默认情况下,适用于所有的请求,但可以使用requestMatcher(RequestMatcher)或者其它相似的方法进行限制。
使用示例:
最基本的基于表单的配置如下。该配置将所有的url访问权限设定为角色名称为"ROLE_USER".同时也定义了内存认证模式:使用用户名"user"和密码&password&,角色"ROLE_USER"来认证。
@Configuration
@EnableWebSecurity
public class FormLoginSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.authorizeRequests()
.antMatchers("/").hasRole("USER")
.formLogin();
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
&配置基于openId的认证方式
&basic示例,不使用attribute exchange
@Configuration
@EnableWebSecurity
public class OpenIDLoginConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) {
.authorizeRequests()
.antMatchers("/").hasRole("USER")
.openidLogin()
.permitAll();
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
.inMemoryAuthentication()
// the username must match the OpenID of the user you are
// logging in with
.withUser("/accounts/o8/id?id=lmkCn9xzPdsxVwG7pjYMuDgNNdASFmobNkcRPaWU")
.password("password")
.roles("USER");
下面展示一个更高级的示例,使用attribute exchange
@Configuration
@EnableWebSecurity
public class OpenIDLoginConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) {
.authorizeRequests()
.antMatchers("/").hasRole("USER")
.openidLogin()
.loginPage("/login")
.permitAll()
.authenticationUserDetailsService(new AutoProvisioningUserDetailsService())
.attributeExchange("/.")
.attribute("email")
.type("http://axschema.org/contact/email")
.required(true)
.attribute("firstname")
.type("http://axschema.org/namePerson/first")
.required(true)
.attribute("lastname")
.type("http://axschema.org/namePerson/last")
.required(true)
.attributeExchange("..")
.attribute("email")
.type("http://schema.openid.net/contact/email")
.required(true)
.attribute("fullname")
.type("http://axschema.org/namePerson")
.required(true)
.attributeExchange("..")
.attribute("email")
.type("http://schema.openid.net/contact/email")
.required(true)
.attribute("fullname")
.type("http://schema.openid.net/namePerson")
.required(true);
public class AutoProvisioningUserDetailsService implements
AuthenticationUserDetailsService&OpenIDAuthenticationToken& {
public UserDetails loadUserDetails(OpenIDAuthenticationToken token) throws UsernameNotFoundException {
return new User(token.getName(), "NOTUSED", AuthorityUtils.createAuthorityList("ROLE_USER"));
增加响应安全报文头
默认情况下当使用WebSecuirtyConfigAdapter的默认构造函数时激活。
仅触发Headers()方法而不触发其它方法或者接受WebSecurityConfigureerAdater默认的,等同于:
@Configuration
@EnableWebSecurity
public class CsrfSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.headers()
.contentTypeOptions();
.xssProtection()
.cacheControl()
.httpStrictTransportSecurity()
.frameOptions()
取消安全报文头,如下:
@Configuration
@EnableWebSecurity
public class CsrfSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.headers().disable()
使用部分安全报文头
触发headers()方法的返回结果,例如,只使用HeaderConfigurer的cacheControll()方法和HeadersConfigurer的frameOptions()方法.
@Configuration
@EnableWebSecurity
public class CsrfSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.headers()
.cacheControl()
.frameOptions()
配置session管理
下面的配置展示了只允许认证用户在同一时间只有一个实例是如何配置的。若一个用户使用用户名为"user"认证并且没有退出,同一个名为&user&的试图再次认证时,第一个用户的session将会强制销毁,并设置到"/login?expired"的url。
@Configuration
@EnableWebSecurity
public class SessionManagementSecurityConfig extends
WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.authorizeRequests()
.anyRequest().hasRole("USER")
.formLogin()
.permitAll()
.sessionManagement()
.maximumSessions(1)
.expiredUrl("/login?expired");
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
当使用SessionManagementConfigurer的maximumSessio(int)时不用忘记为应用配置HttpSessionEventPublisher,这样能保证过期的session能够被清除。
在web.xml中可以这样配置:
&listener&
&listener-class&org.springframework.security.web.session.HttpSessionEventPublisher&/listener-class&;
&/listener&
配置PortMapper
允许配置一个从HttpSecurity的getSharedObject(Class)方法中获取的PortMapper。当http请求跳转到https或者https请求跳转到http请求时(例如我们和requiresChanenl一起使用时),别的提供的SecurityConfigurer对象使用P诶账户的PortMapper作为默认的PortMapper。默认情况下,spring security使用PortMapperImpl来映射http端口8080到https端口8443,并且将http端口的80映射到https的端口443.
配置示例如下,下面的配置将确保在spring security中的http请求端口9090跳转到https端口9443 并且将http端口80跳转到https443端口。
@Configuration
@EnableWebSecurity
public class PortMapperSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.authorizeRequests()
.antMatchers("/").hasRole("USER")
.formLogin()
.permitAll()
// Example portMapper() configuration
.portMapper()
.http(9090).mapsTo(9443)
.http(80).mapsTo(443);
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
配置基于容器的预认证
在这个场景中,servlet容器管理认证。
配置示例:
下面的配置使用HttpServletRequest中的principal,若用户的角色是&ROLE_USER&或者"ROLE_ADMIN",将会返回Authentication结果。
   @Configuration
@EnableWebSecurity
public class JeeSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.authorizeRequests()
.antMatchers("/").hasRole("USER")
// Example jee() configuration
.mappableRoles("ROLE_USER", "ROLE_ADMIN");
开发者希望使用基于容器预认证时,需要在web.xml中配置安全限制。例如:
&login-config&
&auth-method&FORM&/auth-method&
&form-login-config&
&form-login-page&/login&/form-login-page&
&form-error-page&/login?error&/form-error-page&
&/form-login-config&
&/login-config&
&security-role&
&role-name&ROLE_USER&/role-name&
&/security-role&
&security-constraint&
&web-resource-collection&
&web-resource-name&Public&/web-resource-name&
&description&Matches unconstrained pages&/description&
&url-pattern&/login&/url-pattern&
&url-pattern&/logout&/url-pattern&
&url-pattern&/resources/&/url-pattern&
&/web-resource-collection&
&/security-constraint&
&security-constraint&
&web-resource-collection&
&web-resource-name&Secured Areas&/web-resource-name&
&url-pattern&/&/url-pattern&
&/web-resource-collection&
&auth-constraint&
&role-name&ROLE_USER&/role-name&
&/auth-constraint&
&/security-constraint&
配置基于X509的预认证
配置示例,下面的配置试图从X509证书中提取用户名,注意,为完成这个工作,客户端请求证书需要配置到servlet容器中。
@Configuration
@EnableWebSecurity
public class X509SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.authorizeRequests()
.antMatchers("/").hasRole("USER")
// Example x509() configuration
配置Remember-me服务
配置示例,下面的配置展示了如何允许基于token的remember-me的认证。若http参数中包含一个名为&remember-me&的参数,不管session是否过期,用户记录将会被记保存下来。
@Configuration
@EnableWebSecurity
public class RememberMeSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
protected void configure(HttpSecurity http) throws Exception {
.authorizeRequests()
.antMatchers("/").hasRole("USER")
.formLogin()
.permitAll()
// Example Remember Me Configuration
.rememberMe();
限制HttpServletRequest的请求访问
配置示例,最基本的示例是配置所有的url访问都需要角色"ROLE_USER".下面的配置要求每一个url的访问都需要认证,并且授权访问权限给用户"admin"和"user".
@Configuration
@EnableWebSecurity
public class AuthorizeUrlsSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.authorizeRequests()
.antMatchers("/").hasRole("USER")
.formLogin();
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER")
.withUser("adminr")
.password("password")
.roles("ADMIN","USER");
同样,也可以配置多个url。下面的配置要求以/admin/开始的url访问权限为&admin&用户。
@Configuration
@EnableWebSecurity
public class AuthorizeUrlsSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/**").hasRole("USER")
.formLogin();
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER")
.withUser("adminr")
.password("password")
.roles("ADMIN","USER");
注意:匹配起效是按照顺序来的。因此如果下面的配置是无效的,因为满足第一个规则后将不会检查第二条规则:
.authorizeRequests()
.antMatchers("/**").hasRole("USER")
.antMatchers("/admin/**").hasRole("ADMIN")
增加CSRF支持
默认情况下,当使用WebSecurityConfigurerAdapter时的默认构造方法时CSRF是激活的。你可以使用如下方法关闭它:
@Configuration
@EnableWebSecurity
public class CsrfSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.csrf().disable()
增加logout支持
默认支持,当使用WebSecurityConfigurerAdapter时Logout是支持的。当用户发出&/logout&请求时,系统将会销毁session并且清空配置的rememberMe()认证,然后清除SecurityContextHolder,最后跳向logout成功页面或者登陆页面。
@Configuration
@EnableWebSecurity
public class LogoutSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.authorizeRequests()
.antMatchers("/").hasRole("USER")
.formLogin()
// sample logout customization
.deleteCookies("remove")
.invalidateHttpSession(false)
.logoutUrl("/custom-logout")
.logoutSuccessUrl("/logout-success");
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
匿名用户控制
使用WebSecurityConfigurerAdapter时自动绑定。默认情况下,匿名用户有一个AnonymousAuthenticationToken标示,包含角色"ROLE_ANONYMOUS"。
下面的配置展示了如何指定匿名用户应该包含"ROLE_ANON".
@Configuration
@EnableWebSecurity
public class AnononymousSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.authorizeRequests()
.antMatchers("/").hasRole("USER")
.formLogin()
// sample anonymous customization
.anonymous()
.authorities("ROLE_ANON");
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
基于表单的认证
若FormLoginConfigurer的loginpage(String)没有指定,将会产生一个默认的login页面。
示例配置:
@Configuration
@EnableWebSecurity
public class FormLoginSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.authorizeRequests()
.antMatchers("/**").hasRole("USER")
.formLogin();
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
下面的示例展示了自定义的表单认证:
@Configuration
@EnableWebSecurity
public class FormLoginSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.authorizeRequests()
.antMatchers("/").hasRole("USER")
.formLogin()
.usernameParameter("j_username") // default is username
.passwordParameter("j_password") // default is password
.loginPage("/authentication/login") // default is /login with an HTTP get
.failureUrl("/authentication/login?failed") // default is /login?error
.loginProcessingUrl("/authentication/login/process"); // default is /login with an HTTP post
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
配置安全通道
为使配置生效,需至少配置一个通道的映射。
配置示例:
下面例子展示了如何将每个请求都使用https通道。
@Configuration
@EnableWebSecurity
public class ChannelSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.authorizeRequests()
.antMatchers("/**").hasRole("USER")
.formLogin()
.channelSecurity()
.anyRequest().requiresSecure();
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
配置http 基本认证
配置示例:
@Configuration
@EnableWebSecurity
public class HttpBasicSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.authorizeRequests()
.antMatchers("/**").hasRole("USER").and()
.httpBasic();
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
配置要触发的HttpRequest
重写RequestMatcher方法、antMatcher()z、regexMatcher()等。
下面的配置使HttpSecurity接收以"/api/","/oauth/"开头请求。
@Configuration
@EnableWebSecurity
public class RequestMatchersSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.requestMatchers()
.antMatchers("/api/**","/oauth/**")
.authorizeRequests()
.antMatchers("/**").hasRole("USER").and()
.httpBasic();
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
下面的配置和上面的相同:
@Configuration
@EnableWebSecurity
public class RequestMatchersSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.requestMatchers()
.antMatchers("/api/**")
.antMatchers("/oauth/**")
.authorizeRequests()
.antMatchers("/**").hasRole("USER").and()
.httpBasic();
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
同样也可以这样使用:
@Configuration
@EnableWebSecurity
public class RequestMatchersSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
.requestMatchers()
.antMatchers("/api/**")
.requestMatchers()
.antMatchers("/oauth/**")
.authorizeRequests()
.antMatchers("/**").hasRole("USER").and()
.httpBasic();
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
& &本文是从httpSecurity代码中整理得来的,有助于对spring security的全面理解。
阅读(...) 评论()

我要回帖

更多关于 spring security 4 的文章

 

随机推荐