GVKun编程网logo

Java Spring Security:多个HTTP配置不起作用(springsecurity多个登录接口)

25

在这篇文章中,我们将为您详细介绍JavaSpringSecurity:多个HTTP配置不起作用的内容,并且讨论关于springsecurity多个登录接口的相关问题。此外,我们还会涉及一些关于@Pre

在这篇文章中,我们将为您详细介绍Java Spring Security:多个HTTP配置不起作用的内容,并且讨论关于springsecurity多个登录接口的相关问题。此外,我们还会涉及一些关于@PreAuthorize批注在Spring Security中不起作用、java httpclient 关于 spring security 登录问题、java – Spring Security:退出404、java – 如何使用Spring MVC和Spring Security为资源处理程序启用HTTP缓存的知识,以帮助您更全面地了解这个主题。

本文目录一览:

Java Spring Security:多个HTTP配置不起作用(springsecurity多个登录接口)

Java Spring Security:多个HTTP配置不起作用(springsecurity多个登录接口)

我正在尝试使用Spring Security,并且有一个用例,其中我想保护不同的登录页面和不同的URL集。

这是我的配置:

@Configuration@Order(1)public static class ProviderSecurity extends WebSecurityConfigurerAdapter{    @Override    protected void configure(HttpSecurity http) throws Exception {        http            .authorizeRequests()                .antMatchers("/", "/home").permitAll()                .antMatchers("/admin/login").permitAll()                .antMatchers("/admin/**").access("hasRole(''BASE_USER'')")                .and()            .formLogin()                .loginPage("/admin/login").permitAll()                .defaultSuccessUrl("/admin/home")                .failureUrl("/admin/login?error=true").permitAll()                .usernameParameter("username")                .passwordParameter("password")                .and()            .csrf()                                    .and()            .exceptionHandling().accessDeniedPage("/Access_Denied");                }}@Configuration@Order(2)public static class ConsumerSecurity extends WebSecurityConfigurerAdapter {    @Override    protected void configure(HttpSecurity http) throws Exception {        http            .authorizeRequests()                .antMatchers("/consumer/login").permitAll()                .antMatchers("/consumer/**").access("hasRole(''BASE_USER'')")                .anyRequest().authenticated()                .and()            .formLogin()                .loginPage("/consumer/login").permitAll()                .defaultSuccessUrl("/consumer/home")                .failureUrl("/consumer/login?error=true").permitAll()                .usernameParameter("username")                .passwordParameter("password")                .and().csrf()                                .and()            .exceptionHandling().accessDeniedPage("/Access_Denied");    }}

这些类是MultipleHttpSecurityConfig具有注释的另一个类的内部类@EnableWebSecurity

的安全性admin/**工作正常,但所有consumer/**页面均未得到保护,登录页面未发生任何重定向。我搜索了其他答案,但没有一个有效。

答案1

小编典典

看一下Spring Security Reference:

@EnableWebSecuritypublic class MultiHttpSecurityConfig {  @Autowired  public void configureGlobal(AuthenticationManagerBuilder auth) { 1      auth          .inMemoryAuthentication()              .withUser("user").password("password").roles("USER").and()              .withUser("admin").password("password").roles("USER", "ADMIN");  }  @Configuration  @Order(1)                                                        2  public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {      protected void configure(HttpSecurity http) throws Exception {          http              .antMatcher("/api/**")                               3              .authorizeRequests()                  .anyRequest().hasRole("ADMIN")                  .and()              .httpBasic();      }  }      @Configuration                                                   4  public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {      @Override      protected void configure(HttpSecurity http) throws Exception {          http              .authorizeRequests()                  .anyRequest().authenticated()                  .and()              .formLogin();      }  }}

1正常配置身份验证

2创建一个WebSecurityConfigurerAdapter包含的实例,@Order以指定WebSecurityConfigurerAdapter应首先考虑的对象。

3 http.antMatcher指出这HttpSecurity仅适用于以开头的URL/api/

4创建的另一个实例WebSecurityConfigurerAdapter。如果URL不以/api/该配置开头,则将使用此配置。此配置被认为是之后的,ApiWebSecurityConfigurationAdapter因为它的@Order值是after 1(没有@Order默认值是last)。

您的第二个配置未使用,因为您的第一个配置匹配/**(未antMatcher配置)。而且您的第一个配置仅限制/admin/**,默认情况下允许所有其他URL。

@PreAuthorize批注在Spring Security中不起作用

@PreAuthorize批注在Spring Security中不起作用

我发现了许多类似的问题,但都没有解决我的问题。我的问题是ROLE_USER可以访问的功能ROLE_ADMIN

我的spring-security.xml代码如下。

<beans xmlns="http://www.springframework.org/schema/beans"   xmlns:s="http://www.springframework.org/schema/security"   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.0.xsd"><s:http auto-config="true" use-expressions="true">    <s:intercept-url pattern="/index.jsp" access="permitAll" />    <s:intercept-url pattern="/welcome*" access="hasRole(''ROLE_USER'')" />    <s:intercept-url pattern="/helloadmin*" access="hasRole(''ROLE_ADMIN'')" />    <s:form-login login-page="/login" default-target-url="/welcome"        authentication-failure-url="/loginfailed" />    <s:logout logout-success-url="/logout" /></s:http><s:authentication-manager>  <s:authentication-provider>    <s:user-service>        <s:user name="asif" password="123456" authorities="ROLE_USER,ROLE_ADMIN" />        <s:user name="raheel" password="123456" authorities="ROLE_USER" />              </s:user-service>  </s:authentication-provider></s:authentication-manager>

当我添加<s:global-method-security pre-post-annotations="enabled"/>
我的代码时显示找不到资源错误,并且当我删除我的代码时成功执行但ROLE_USER可以访问ROLE_ADMIN函数

我的控制器功能是。

@PreAuthorize("hasRole(''ROLE_ADMIN'')")@RequestMapping(value="/delete", method = RequestMethod.GET)public String DeleteAll(ModelMap model, Principal principal ) {    org.springframework.security.core.userdetails.User activeUser = (org.springframework.security.core.userdetails.User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();    System.out.println("Active user is "+activeUser.getUsername()+"Authorities are "+activeUser.getAuthorities());    return "deleteUsers";}

答案1

小编典典

你应该有

<s:global-method-security pre-post-annotations="enabled"/>

如果您希望@PreAuthorize注释起作用。


回答评论:

看来您缺少spring-aop依赖性。

如果您正在使用Maven,则需要:

<dependency>    <groupId>org.springframework</groupId>    <artifactId>spring-aop</artifactId>    <version>${org.springframework.version}</version></dependency>

如果没有,你可以从这里拿到罐子。

java httpclient 关于 spring security 登录问题

java httpclient 关于 spring security 登录问题

NameValuePair[] data = {new NameValuePair("j_username","luson"), new NameValuePair("j_password","123")};
HttpClient httpClient = new HttpClient();  
PostMethod postMethod = new PostMethod("http://localhost:8080/Kaoqin/spring_security_login");  
postMethod.setRequestBody(data); 
int statusCode = httpClient.executeMethod(postMethod);  
能帮忙看一下这段代码吗,为什么状态码 satusCode 为 200,而不是应该为 302 ,我用该账号登录成功后,应该会重定向到主页的呀? 

java – Spring Security:退出404

java – Spring Security:退出404

当我尝试访问我的 spring应用程序的注销URL时,我的服务器日志中发现了一个404错误,并且在dispatcherServlet中使用名称为“mvc-dispatcher”的URI [/ logout]找到HTTP请求.

我已经尝试了Call to j_spring_security_logout not working,Issue with Spring security’s logout和几乎所有相关的结果.

我正在包括完整的配置文件,因为Spring xml结构对我来说还不是很清楚.

我的安全配置:

<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-3.2.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security.xsd">

    <http pattern="/resources/**" security="none" />

    <http auto-config="true">
        <intercept-url pattern="/login*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
        <intercept-url pattern="/**" access="ROLE_USER" />
        <form-login login-page="/login" default-target-url="/"/>
        <logout logout-url="/logout" />
        <csrf />
    </http>

    <global-method-security secured-annotations="enabled" />

    <authentication-manager>
        <authentication-provider user-service-ref="userDetailsService" />
    </authentication-manager>

</beans:beans>

我的web.xml是这样的:

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <display-name>XYZ</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/*-config.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <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>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.dispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

如何使注销页面工作?

解决方法

如果您使用CSRF注销,则必须执行POST.见 http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#csrf-logout

java – 如何使用Spring MVC和Spring Security为资源处理程序启用HTTP缓存

java – 如何使用Spring MVC和Spring Security为资源处理程序启用HTTP缓存

我希望为某些静态资源(如图像)启用HTTP缓存,Spring Security对此进行了限制. (这些资源不是安全性关键,但也不应公开访问).如何避免Spring Security添加禁用缓存的HTTP响应头?

如果我将SetCachePeriod()添加到WebMvcConfigurerAdapter.addResourceHandlers()中的资源处理程序注册中,如下所示:

registry.addResourceHandler("/static/**")
  .addResourceLocations("classpath:/static/").setCachePeriod(3600);

资源仍然返回,并带有以下标题,禁用高速缓存:

Cache-Control: max-age=3600,must-revalidate
Expires: Mon,04 Aug 2014 07:45:36 GMT
Pragma: no-cache

我想避免在项目中引入任何XML配置,目前仅使用Java注释配置.

有没有比扩展Spring资源处理程序更好的解决方案?

解决方法

您可以使用webContentInterceptor资源来允许静态资源缓存.
<mvc:interceptors>
    <mvc:interceptor>
    <mvc:mapping path="/static/*"/>
        <bean id="webContentInterceptor">
            <property name="cacheSeconds" value="31556926"/>
            <property name="useExpiresHeader" value="true"/>
            <property name="useCacheControlHeader" value="true"/>
            <property name="useCacheControlNoStore" value="true"/>
        </bean>
   </mvc:interceptor>
</mvc:interceptors>

使用注释配置缓存拦截器是按照以下方式完成的.
在Web配置类中,您可以为WebContentInterceptor类添加一个bean,并将其添加到拦截器列表中.

@Bean
public WebContentInterceptor webContentInterceptor() {
    WebContentInterceptor interceptor = new WebContentInterceptor();
    interceptor.setCacheSeconds(31556926);
    interceptor.setUseExpiresHeader(true);;
    interceptor.setUseCacheControlHeader(true);
    interceptor.setUseCacheControlNoStore(true);
    return interceptor;
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(webContentInterceptor());
}

参考this site看看它是如何完成的.

我们今天的关于Java Spring Security:多个HTTP配置不起作用springsecurity多个登录接口的分享就到这里,谢谢您的阅读,如果想了解更多关于@PreAuthorize批注在Spring Security中不起作用、java httpclient 关于 spring security 登录问题、java – Spring Security:退出404、java – 如何使用Spring MVC和Spring Security为资源处理程序启用HTTP缓存的相关信息,可以在本站进行搜索。

本文标签: