GVKun编程网logo

Spring Security配置-HttpSecurity与WebSecurity(spring security 配置)

14

本文将带您了解关于SpringSecurity配置-HttpSecurity与WebSecurity的新内容,同时我们还将为您解释springsecurity配置的相关知识,另外,我们还将为您提供关于

本文将带您了解关于Spring Security配置-HttpSecurity与WebSecurity的新内容,同时我们还将为您解释spring security 配置的相关知识,另外,我们还将为您提供关于org.springframework.security.config.annotation.web.builders.HttpSecurity的实例源码、security5 + spring boot , 实现的 WebSecurityConfigurerAdapter 接口,配置文件不生效、Spring Security 3.2.1具有不同WebSecurityConfigurerAdapters的多个登录表单、Spring Security 4自定义登录j_spring_security_check返回http 302的实用信息。

本文目录一览:

Spring Security配置-HttpSecurity与WebSecurity(spring security 配置)

Spring Security配置-HttpSecurity与WebSecurity(spring security 配置)

我只需要了解Spring Security Configuration中的内容。使用下面的示例…

@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {    @Override    protected void configure(HttpSecurity http) throws Exception {        http            .httpBasic()            .and()            .authorizeRequests().antMatchers("/secret/**").authenticated()            .and()            .authorizeRequests().antMatchers("/**").permitAll();    }    @Override    public void configure(WebSecurity web) throws Exception {        web.ignoring().antMatchers("/resources/**");    }}

configure(WebSecurity web)方法的目的是什么?

我不能只是添加/resources/**configure(HttpSecurityhttp)方法,在这条线.authorizeRequests().antMatchers("/**","/resources/**").permitAll(); 应该不是它的工作相同,即允许所有的请求/resources/**没有任何身份验证?

答案1

小编典典

WebSecurity ignoring()方法的常规用法 省略了Spring Security, 并且Spring
Security的功能均不可用。WebSecurity基于HttpSecurity。

@Overridepublic void configure(WebSecurity web) throws Exception {    web        .ignoring()        .antMatchers("/resources/**")        .antMatchers("/publics/**");}@Overrideprotected void configure(HttpSecurity http) throws Exception {    http        .authorizeRequests()        .antMatchers("/admin/**").hasRole("ADMIN")        .antMatchers("/publics/**").hasRole("USER") // no effect        .anyRequest().authenticated();}

上面的示例中的WebSecurity让Spring忽略/resources/**/publics/**。因此.antMatchers("/publics/**").hasRole("USER"),不
考虑 HttpSecurity中的。

这将完全省略来自安全过滤器链的请求模式。请注意,与此路径匹配的所有内容都将不应用身份验证或授权服务,并且可以自由访问。

configure(HttpSecurity)允许根据选择匹配在 资源级别 配置基于Web的安全性-
例如,以下示例将以URL开头的URL限制为/admin/具有 ADMIN角色的 用户,并声明需要 成功进行身份验证的 所有其他URL

configure(WebSecurity)用于 影响全局安全性的
配置设置(忽略资源,设置调试模式,通过实现自定义防火墙定义拒绝请求)。例如,以下方法将导致 以身份验证为 开头的所有请求/resources/都被
忽略

org.springframework.security.config.annotation.web.builders.HttpSecurity的实例源码

org.springframework.security.config.annotation.web.builders.HttpSecurity的实例源码

项目:Spring-Security-Third-Edition    文件:SecurityConfig.java   
/**
 * This is the equivalent to:
 * <pre>
 *     <http pattern="/resources/**" security="none"/>
 *     <http pattern="/css/**" security="none"/>
 *     <http pattern="/webjars/**" security="none"/>
 * </pre>
 *
 * @param web
 * @throws Exception
 */
@Override
public void configure(final WebSecurity web) throws Exception {

    // Ignore static resources and webjars from Spring Security
    web.ignoring()
            .antMatchers("/resources/**")
            .antMatchers("/css/**")
            .antMatchers("/webjars/**")
    ;

    // Thymeleaf needs to use the Thymeleaf configured FilterSecurityInterceptor
    // and not the default Filter from AutoConfiguration.
    final HttpSecurity http = getHttp();
    web.postBuildAction(() -> {
        web.securityInterceptor(http.getSharedobject(FilterSecurityInterceptor.class));
    });
}
项目:chatbot    文件:Application.java   
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/","/assets/**/*","/js/*","/images/**/*","/Feedback","/webhook","/fbwebhook","/slackwebhook","/embed").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .defaultSuccessUrl("/admin")
            .loginPage("/login")
            .permitAll()
            .and()
            .logout()
            .permitAll();
    http.headers().frameOptions().disable();
}
项目:mirrorgate    文件:RestConfig.java   
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .addFilterBefore(new HeaderSecurityFilter(),SecurityContextHolderAwareRequestFilter.class)
            .cors()
                .and()
            .csrf()
                .disable()
            .authorizeRequests()
                .antMatchers("/health").permitAll()
                .antMatchers("/websocket").permitAll()
                .antMatchers(HttpMethod.OPTIONS,"**").permitAll()
                .antMatchers(HttpMethod.POST,"/api/**").hasAuthority(SecurityAuthoritiesEnum.COLLECTOR.toString())
                .antMatchers(HttpMethod.DELETE,"/api/**").hasAuthority(SecurityAuthoritiesEnum.COLLECTOR.toString())
                .antMatchers(HttpMethod.POST,"/reviews/**").hasAuthority(SecurityAuthoritiesEnum.REGULAR.toString())
                .antMatchers(HttpMethod.GET,"/dashboards/**").hasAnyAuthority(SecurityAuthoritiesEnum.REGULAR.toString(),SecurityAuthoritiesEnum.SCREEN.toString())
                .antMatchers(HttpMethod.GET,"/emitter/**").hasAnyAuthority(SecurityAuthoritiesEnum.REGULAR.toString(),SecurityAuthoritiesEnum.SCREEN.toString())
                .antMatchers(HttpMethod.POST,"/dashboards/**").hasAuthority(SecurityAuthoritiesEnum.REGULAR.toString())
                .antMatchers(HttpMethod.DELETE,"/dashboards/**").hasAuthority(SecurityAuthoritiesEnum.REGULAR.toString())
                .antMatchers(HttpMethod.PUT,"/dashboards/**").hasAuthority(SecurityAuthoritiesEnum.REGULAR.toString());
}
项目:Spring-Security-Third-Edition    文件:SecurityConfig.java   
/**
 * This is the equivalent to:
 * <pre>
 *     <http pattern="/resources/**" security="none"/>
 *     <http pattern="/css/**" security="none"/>
 *     <http pattern="/webjars/**" security="none"/>
 * </pre>
 *
 * @param web WebSecurity
 * @throws Exception
 */
@Override
public void configure(final WebSecurity web) throws Exception {
    web.ignoring()
            .antMatchers("/resources/**")
            .antMatchers("/css/**")
            .antMatchers("/webjars/**")
    ;

    // Thymeleaf needs to use the Thymeleaf configured FilterSecurityInterceptor
    // and not the default Filter from AutoConfiguration.
    final HttpSecurity http = getHttp();
    web.postBuildAction(() -> {
        web.securityInterceptor(http.getSharedobject(FilterSecurityInterceptor.class));
    });
}
项目:springboot-security-wechat    文件:SecurityConfig.java   
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            //任何访问都必须授权
            .anyRequest().fullyAuthenticated()
            //配置那些路径可以不用权限访问
            .mvcMatchers("/login","/login/wechat").permitAll()
            .and()
            .formLogin()
            //登陆成功后的处理,因为是API的形式所以不用跳转页面
            .successHandler(new MyAuthenticationSuccessHandler())
            //登陆失败后的处理
            .failureHandler(new MySimpleUrlAuthenticationFailureHandler())
            .and()
            //登出后的处理
            .logout().logoutSuccessHandler(new RestlogoutSuccessHandler())
            .and()
            //认证不通过后的处理
            .exceptionHandling()
            .authenticationEntryPoint(new RestAuthenticationEntryPoint());
    http.addFilterat(myFilterSecurityInterceptor,FilterSecurityInterceptor.class);
    http.addFilterBefore(ssoFilter(),BasicAuthenticationFilter.class);
    //http.csrf().csrftokenRepository(CookieCsrftokenRepository.withHttpOnlyFalse());
    http.csrf().disable();
}
项目:Spring-5.0-Cookbook    文件:AppSecurityModelE2.java   
@Override
protected void configure(HttpSecurity http) throws Exception {
        http
          .authorizeRequests()
          .antMatchers("/login**","/after**").permitAll()
          .anyRequest().authenticated()
          .and()
          .formLogin()
          .loginPage("/login.html")
          .defaultSuccessUrl("/deptform.html")
          .failureUrl("/login.html?error=true")
          .successHandler(customSuccessHandler)
          .and()
          .logout().logoutUrl("/logout.html")
          .logoutSuccessHandler(customlogoutHandler);

        http.csrf().disable();
    }
项目:Spring-Security-Third-Edition    文件:SecurityConfig.java   
/**
     * This is the equivalent to:
     * <pre>
     *     <http pattern="/resources/**" security="none"/>
     *     <http pattern="/css/**" security="none"/>
     *     <http pattern="/webjars/**" security="none"/>
     * </pre>
     *
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(final WebSecurity web) throws Exception {

        // Ignore static resources and webjars from Spring Security
        web.ignoring()
                .antMatchers("/resources/**")
                .antMatchers("/css/**")
                .antMatchers("/webjars/**")
        ;

        // Thymeleaf needs to use the Thymeleaf configured FilterSecurityInterceptor
        // and not the default Filter from AutoConfiguration.
        final HttpSecurity http = getHttp();
        web.postBuildAction(() -> {
//            web.securityInterceptor(http.getSharedobject(FilterSecurityInterceptor.class));
            FilterSecurityInterceptor fsi = http.getSharedobject(FilterSecurityInterceptor.class);
            fsi.setSecurityMetadataSource(MetadataSource);
            web.securityInterceptor(fsi);
        });
    }
项目:Building-Web-Apps-with-Spring-5-and-Angular    文件:ResourceServerOAuth2Config.java   
@Override
 public void configure(final HttpSecurity http) throws Exception {
    http
        .requestMatchers().antMatchers("/doctor/**","/rx/**","/account/**")
        .and()
        .authorizeRequests()
        .antMatchers(HttpMethod.GET,"/doctor/**").access("#oauth2.hasScope('doctor') and #oauth2.hasScope('read')")
.antMatchers(HttpMethod.POST,"/doctor/**").access("#oauth2.hasScope('doctor') and #oauth2.hasScope('write')")
.antMatchers(HttpMethod.GET,"/rx/**").access("#oauth2.hasScope('doctor') and #oauth2.hasScope('read')")
.antMatchers(HttpMethod.POST,"/rx/**").access("#oauth2.hasScope('doctor') and #oauth2.hasScope('write')")   
.antMatchers("/account/**").permitAll()
.and()
.exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler())
.and()
.csrf().disable();

 }
项目:AntiSocial-Platform    文件:SecurityConfiguration.java   
@Override
protected void configure(HttpSecurity http) throws Exception{
    http.addFilterBefore(characterEncodingFilter(),CsrfFilter.class);
    http.authorizeRequests()
            .antMatchers("/","/category/**","/article/add","/user/update").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN') or hasRole('ROLE_MODERATOR')")
            .antMatchers("/admin","/admin/**").access("hasRole('ROLE_ADMIN')")
            .and()
            .formLogin()
            .loginPage("/login")
            .usernameParameter("ssoId")
            .passwordParameter("password")
            .failureHandler(new CustomAuthenticationFailureHandler())
            .defaultSuccessUrl("/")
            .and()
            .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessUrl("/login?logout").deleteCookies("JSESSIONID")
            .invalidateHttpSession(true)
            .and()
            .rememberMe().tokenRepository(persistentTokenRepository()).tokenValiditySeconds(86400)
            .and()
            .csrf()
            .and()
            .exceptionHandling().accessDeniedPage("/error");

    http.sessionManagement().maximumSessions(1).sessionRegistry(sessionRegistry());
}
项目:Spring-5.0-Cookbook    文件:AppSecurityModelD.java   
@Override
protected void configure(HttpSecurity http) throws Exception {
        http
          .authorizeRequests()
          .antMatchers("/login**","/after**").permitAll()
          .anyRequest().authenticated()
          .and()
          .formLogin()
          .loginPage("/login.html")
          .defaultSuccessUrl("/deptform.html")
          .failureUrl("/login.html?error=true")
          .successHandler(customSuccessHandler)
          .and()
          .logout().logoutUrl("/logout.html")
          .logoutSuccessHandler(customlogoutHandler);

        http.csrf().disable();
    }
项目:jersey-jwt-springsecurity    文件:WebSecurityConfig.java   
@Override
protected void configure(HttpSecurity http) throws Exception {

    http
        .csrf()
            .disable()
        .exceptionHandling()
            .authenticationEntryPoint(authenticationEntryPoint)
        .and()
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
            .authorizeRequests()
                .antMatchers("/api/auth","/api/users/me","/api/greetings/public").permitAll()
                .anyRequest().authenticated()
        .and()
            .addFilterBefore(authenticationTokenFilterBean(),UsernamePasswordAuthenticationFilter.class);
}
项目:spring-io    文件:MicroserviceSecurityConfiguration.java   
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf()
        .disable()
        .headers()
        .frameOptions()
        .disable()
    .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()
        .authorizeRequests()
        .antMatchers("/api/**").authenticated()
        .antMatchers("/management/health").permitAll()
        .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/swagger-resources/configuration/ui").permitAll()
    .and()
        .apply(securityConfigurerAdapter());
}
项目:homer    文件:SpringSecurityConfig.java   
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
        .authorizeRequests()
        .antMatchers("/","/public/**","/resources/**","/resources/public/**","/css/**","/js/**","/webjars/**").permitAll()
        .antMatchers("/","/home","/about").permitAll()
        // .antMatchers("admin/**","api/**","project/**").hasRole("ADMIN")
        // .antMatchers("/user/**","project/**","api/projects/**").hasRole("USER")
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/login")
        .defaultSuccessUrl("/",true)
        .failureUrl("/login?error")
        .failureHandler(customAuthenticationHandler)
        .permitAll()
        .and()
        .logout()
        .permitAll()
        .and()
        .exceptionHandling().accessDeniedHandler(accessDeniedHandler);
}
项目:boot-mon    文件:BootmonServerSecurityConfig.java   
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .headers()
            .frameOptions()
            .disable();

    if (properties.isSecurityEnabled()) {
        http
                .authorizeRequests()
                .anyRequest()
                .fullyAuthenticated()
                .and()
                .httpBasic();
    }
}
项目:OMIPlatform    文件:TZResourcesServerConfig.java   
@Override
public void configure(HttpSecurity http) throws Exception {

    http.formLogin()
            .loginProcessingUrl("/api/authentication/form") //认证URL
            .loginPage("/api/authentication/require") //登录页
            .successHandler(tzAuthenticationSuccessHandler) //登录成功处理器
            .failureHandler(tzAuthenticationFailureHandler)
            .and()
            .authorizeRequests()
            .antMatchers(
                    "/api/authentication/form","/api/authentication/require","/api/imgs/**","/templates/**","/api/resources/menus"
                    )
            .permitAll()
            .anyRequest()
            .access("@rbacService.havePermission(request,authentication)");
}
项目:Using-Spring-Oauth2-to-secure-REST    文件:ResourceConfig.java   
@Override
public void configure(HttpSecurity http) throws Exception {
    http

            .requestMatcher(new OAuthRequestedMatcher())
            .csrf().disable()
            .anonymous().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS).permitAll()
            // when restricting access to 'Roles' you must remove the "ROLE_" part role
            // for "ROLE_USER" use only "USER"
            .antMatchers("/api/hello").access("hasAnyRole('USER')")
            .antMatchers("/api/me").hasAnyRole("USER","ADMIN")
            .antMatchers("/api/admin").hasRole("ADMIN")
            // use the full name when specifying authority access
            .antMatchers("/api/registerUser").hasAuthority("ROLE_REGISTER")
            // restricting all access to /api/** to authenticated users
            .antMatchers("/api/**").authenticated();
}
项目:OutsourcedProject    文件:WebSecurityConfig.java   
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/xxx/**")
            .access("hasRole('ROLE_USER')")
            .anyRequest()
            .authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .failureUrl("/login?error")
            .permitAll()
            .and()
            .rememberMe()
            .tokenValiditySeconds(60 * 60 * 24 * 7)
            .useSecureCookie(true)
            .key("remember-me")
            .rememberMeCookieName("remember-me")
            .and()
            .logout()
            .deleteCookies("remember-me")
            .permitAll();
}
项目:Android_watch_magpie    文件:OAuth2SecurityConfiguration.java   
@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();

    http
    .authorizeRequests()
        .antMatchers("/oauth/token").anonymous();

    http
    .authorizeRequests()
            .antMatchers(HttpMethod.GET,"/**")
            .access("#oauth2.hasScope('read')");

    http
    .authorizeRequests()
            .antMatchers("/**")
            .access("#oauth2.hasScope('write')");
}
项目:document-management-store-app    文件:SpringSecurityConfiguration.java   
@Override
protected void configure(HttpSecurity http) throws Exception {
    filter.setAuthenticationManager(authenticationManager());

    http.headers().cacheControl().disable();

    http
        .addFilter(filter)
        .sessionManagement().sessionCreationPolicy(STATELESS).and()
        .csrf().disable()
        .formLogin().disable()
        .logout().disable()
        .authorizeRequests()
        .antMatchers("/swagger-ui.html","/webjars/springfox-swagger-ui/**","/swagger-resources/**","/v2/**","/health","/info"
        ).permitAll()
        .anyRequest().authenticated();
}
项目:springuni-particles    文件:AuthSecurityConfiguration.java   
@Override
protected void customizeRememberMe(HttpSecurity http) throws Exception {
  UserDetailsService userDetailsService = lookup("userDetailsService");
  PersistentTokenRepository persistentTokenRepository = lookup("persistentTokenRepository");
  AbstractRememberMeServices rememberMeServices = lookup("rememberMeServices");
  RememberMeAuthenticationFilter rememberMeAuthenticationFilter =
      lookup("rememberMeAuthenticationFilter");

  http.rememberMe()
      .userDetailsService(userDetailsService)
      .tokenRepository(persistentTokenRepository)
      .rememberMeServices(rememberMeServices)
      .key(rememberMeServices.getKey())
      .and()
      .logout()
      .logoutUrl(logoUT_ENDPOINT)
      .and()
      .addFilterat(rememberMeAuthenticationFilter,RememberMeAuthenticationFilter.class);
}
项目:Spring-Security-Third-Edition    文件:SecurityConfig.java   
/**
 * HTTP Security configuration
 *
 * <pre><http auto-config="true"></pre> is equivalent to:
 * <pre>
 *  <http>
 *      <form-login />
 *      <http-basic />
 *      <logout />
 *  </http>
 * </pre>
 *
 * Which is equivalent to the following JavaConfig:
 *
 * <pre>
 *     http.formLogin()
 *          .and().httpBasic()
 *          .and().logout();
 * </pre>
 *
 * @param http HttpSecurity configuration.
 * @throws Exception Authentication configuration exception
 *
 * @see <a href="http://docs.spring.io/spring-security/site/migrate/current/3-to-4/html5/migrate-3-to-4-jc.html">
 *     Spring Security 3 to 4 migration</a>
 */
@Override
protected void configure(final HttpSecurity http) throws Exception {
    http.authorizeRequests()
            // FIXME: Todo: Allow anyone to use H2 (NOTE: NOT FOR PRODUCTION USE EVER !!! )
            .antMatchers("/admin/h2/**").permitAll()

            .antMatchers("/").permitAll()
            .antMatchers("/login/*").permitAll()
            .antMatchers("/logout").permitAll()
            .antMatchers("/signup/*").permitAll()
            .antMatchers("/errors/**").permitAll()
            .antMatchers("/admin/*").hasRole("ADMIN")
            .antMatchers("/events/").hasRole("ADMIN")
            .antMatchers("/**").hasRole("USER")

            .and().exceptionHandling().accessDeniedPage("/errors/403")

            .and().formLogin()
            .loginPage("/login/form")
            .loginProcessingUrl("/login")
            .failureUrl("/login/form?error")
            .usernameParameter("username")
            .passwordParameter("password")
            .defaultSuccessUrl("/default",true)
            .permitAll()

            .and().logout()
            .logoutUrl("/logout")
            .logoutSuccessUrl("/login/form?logout")
            .permitAll()

            .and().anonymous()

            // CSRF is enabled by default,with Java Config
            .and().csrf().disable();

    // Enable <frameset> in order to use H2 web console
    http.headers().frameOptions().disable();
}
项目:saluki    文件:ResourceServerConfiguration.java   
@Override
public void configure(HttpSecurity http) throws Exception {
  http.anonymous()//
      .disable()//
      .requestMatchers()//
      .antMatchers("/api/**")//
      .and().authorizeRequests()//
      .antMatchers("/api/**")//
      .fullyAuthenticated()//
      .and().exceptionHandling()//
      .accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
项目:springboot-sec-tutor    文件:SecurityConfig.java   
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .and()
            .logout().permitAll()
            .and()
            // Security Headers http://docs.spring.io/spring-security/site/docs/current/reference/html/headers.html
            .headers()
                // Cache-Control: no-cache set by default spring boot security
                //.cacheControl()
                //.and()
                // x-frame-options: DENY set by default spring boot security
                .frameOptions().sameOrigin()
                // X-Content-Type-Options: nosniff set by default spring boot security
                //.contentTypeOptions()
                //.and()
                // Content-Security-Policy
                .contentSecurityPolicy("default-src 'self'; script-src 'self' 'unsafe-inline'; report-uri /csp")
            // HSTS (you may consider setting this header in the ssl handling part of your app e.g. apache,nginix)
            .and()
                // be careful when deploying this 2 years policy because it will prevent your customers browsers from visiting your page without ssl
                .httpStrictTransportSecurity()
                .maxAgeInSeconds(63072000)
            // HPKP (you may consider setting this header in the ssl handling part of your app e.g. apache,nginix)
            .and()
                .httpPublicKeyPinning()
                .addSha256Pins("pGO1ErsUFSrId1hozlZOfyYOsE8mdiDgLyR89CtHK8E=")
                .maxAgeInSeconds(63072000)
                // remove reportOnly when certificates (including backup certificates!) including thoughtfully made deployment strategy worked out
                .reportOnly(true)
                .reportUri("/pkp");
}
项目:uis    文件:WebSecurityConfig.java   
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.headers().frameOptions().disable();

    http
           .csrf()
               .ignoringAntMatchers("/rest/**") //disable csrf for rest
               .ignoringAntMatchers("/console/**") //disable the database
               .ignoringAntMatchers("/logout"); // allow double logout

       http
           .authorizeRequests()
               .antMatchers("/").permitAll()
               .antMatchers("/rest/**").permitAll()   //do not require passwords for rest
               .antMatchers("/public/**").permitAll()
               .antMatchers("/min/**").permitAll()
               .antMatchers("/webjars/**").permitAll()
               .antMatchers("/node_modules/**").permitAll()
               .antMatchers("/console/**").permitAll()
               .antMatchers("/account_activation/**").permitAll()
               .antMatchers("/admin/**").hasRole(Role.ADMIN.name())
               .antMatchers("/lecturer/**").hasRole(Role.LECTURER.name())
               .antMatchers("/student/**").hasRole(Role.STUDENT.name())
               .anyRequest().authenticated();

       http
           .formLogin()
               .loginPage("/login")
               .loginPage("/login?notLoggedIn")
               .failureUrl("/login?error")
               .defaultSuccessUrl("/")
               .permitAll();

       http
           .logout()
               .logoutSuccessUrl("/login?loggedOut")
               .permitAll();
   }
项目:email-service    文件:SecurityConfig.java   
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers(POST,"/email/keys").hasAuthority(CREATE_API_KEYS_PRIVILEGE.name())
        .antMatchers(POST,"/email/templates").hasAuthority(CREATE_TEMPLATES_PRIVILEGE.name())
        .antMatchers(GET,"/email/templates/**").hasAuthority(READ_TEMPLATES_PRIVILEGE.name())
        .anyRequest().fullyAuthenticated()
        .and().httpBasic()
        .and().csrf().disable();
}
项目:rest-api-jwt-spring-security    文件:WebSecurityConfig.java   
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            // we don't need CSRF because our token is invulnerable
            .csrf().disable()

            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()

            // don't create session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

            .authorizeRequests()
            //.antMatchers(HttpMethod.OPTIONS,"/**").permitAll()

            // allow anonymous resource requests
            .antMatchers(
                    HttpMethod.GET,"/","/v2/api-docs",// swagger
                    "/webjars/**",// swagger-ui webjars
                    "/swagger-resources/**",// swagger-ui resources
                    "/configuration/**",// swagger configuration
                    "/*.html","/favicon.ico","/**/*.html","/**/*.css","/**/*.js"
            ).permitAll()
            .antMatchers("/api/auth/**").permitAll()
            .anyRequest().authenticated();

    // Custom JWT based security filter
    httpSecurity
            .addFilterBefore(authenticationTokenFilterBean(),UsernamePasswordAuthenticationFilter.class);

    // disable page caching
    httpSecurity.headers().cacheControl();
}
项目:markdown-redactor    文件:RestSecurityConfig.java   
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .antMatcher("/api/**")
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS,"/api/**").permitAll()
            .antMatchers(HttpMethod.GET,"/api").permitAll()
            .antMatchers(HttpMethod.POST,"/api/users").permitAll()
            .anyRequest().authenticated()
            .and().httpBasic().and().cors();
}
项目:spring-ddd-bank    文件:WebSecurityConfig.java   
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/").permitAll()
        .antMatchers("/bank/**").hasRole(BANK_ROLE)
        .antMatchers("/client/**").hasRole(CLIENT_ROLE)
        .anyRequest().authenticated()
        .and().httpBasic() //Authenticate with username and password.
        //For REST services disable CSRF protection. 
        //See https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#when-to-use-csrf-protection
        .and().csrf().disable()
        ;
}
项目:Armory    文件:SecurityConfiguration.java   
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .addFilterBefore(corsFilter,UsernamePasswordAuthenticationFilter.class)
        .exceptionHandling()
        .authenticationEntryPoint(http401UnauthorizedEntryPoint())
    .and()
        .csrf()
        .disable()
        .headers()
        .frameOptions()
        .disable()
    .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()
        .authorizeRequests()
        .antMatchers("/api/register").permitAll()
        .antMatchers("/api/activate").permitAll()
        .antMatchers("/api/authenticate").permitAll()
        .antMatchers("/api/account/reset_password/init").permitAll()
        .antMatchers("/api/account/reset_password/finish").permitAll()
        .antMatchers("/api/profile-info").permitAll()
        .antMatchers("/api/**").authenticated()
        .antMatchers("/websocket/tracker").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/websocket/**").permitAll()
        .antMatchers("/management/health").permitAll()
        .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/v2/api-docs/**").permitAll()
        .antMatchers("/swagger-resources/configuration/ui").permitAll()
        .antMatchers("/swagger-ui/index.html").hasAuthority(AuthoritiesConstants.ADMIN)
    .and()
        .apply(securityConfigurerAdapter());

}
项目:spring-security-oauth2-boot    文件:ActuatorSecurityConfiguration.java   
@Override
protected void configure(HttpSecurity http) throws Exception {
    // @formatter:off
    http
        .requestMatcher(EndpointRequest.toAnyEndpoint())
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .httpBasic();
    // @formatter:on
}
项目:spring-security-oauth2-boot    文件:SampleSecureOAuth2ResourceApplication.java   
@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .antMatcher("/flights/**")
        .authorizeRequests()
            .anyRequest().authenticated();
}
项目:OAuth-2.0-Cookbook    文件:OAuth2ResourceServer.java   
@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .anyRequest().authenticated().and()
        .requestMatchers().antMatchers("/api/**");
}
项目:OAuth-2.0-Cookbook    文件:OAuth2ResourceServer.java   
@Override
public void configure(HttpSecurity http) throws Exception {
    //@formatter:off
    http.authorizeRequests()
        .anyRequest()
        .authenticated()
    .and()
        .requestMatchers()
        .antMatchers("/api/**");
    //@formatter:on
}
项目:spring-boot-jwt-jpa    文件:WebSecurityConfig.java   
@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.headers().defaultsdisabled().cacheControl();//加入Cache相关HTTP头,禁用浏览器缓存
        httpSecurity.formLogin().disable();//禁用org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
        httpSecurity.httpBasic().disable();//禁用org.springframework.security.web.authentication.www.BasicAuthenticationFilter
        httpSecurity.csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // don't create session

        httpSecurity.authorizeRequests()
                // allow anonymous resource requests
                .antMatchers(
//                        HttpMethod.GET,"/**/*.js"
                ).permitAll()
                .antMatchers(HttpMethod.GET,"/v1/**").permitAll()
                .antMatchers("/",//一个系统,正常情况下首页都是可以访问的
                        "/" + authPath,"/sys/auth/init").permitAll()
                .anyRequest().authenticated();

        /**
         * 每次请求过来时,我们将获取请求的Authorization头部存有的jwt,并提取相应的信息,* 如果当前security的上下文还没有认证对应的用户信息并且token是有效的,* 那么就将认证成功所返回的信息设置在security的上下文中,* 最后再将请求传递给下一个过滤器
         */
        httpSecurity.addFilterBefore(authenticationTokenFilterBean(),UsernamePasswordAuthenticationFilter.class);
        // custom JSON based authentication by POST of {"username":"<name>","password":"<password>"} which sets the token header upon authentication
//        httpSecurity.addFilterBefore(loginFilter(),UsernamePasswordAuthenticationFilter.class);

        // custom Token based authentication based on the header prevIoUsly given to the client
//        httpSecurity.addFilterBefore(new StatelesstokenAuthenticationFilter(tokenAuthenticationService),UsernamePasswordAuthenticationFilter.class);

    }
项目:gamesboard    文件:copyOfRestLoginSecurityContext.java   
@Override
  protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
        .httpBasic()
        .and().authorizeRequests()
              .antMatchers("/login/**","/profile/**").hasRole("USER")
              .and().authorizeRequests().anyRequest().permitAll()
             /* .and()
          .apply(new SpringSocialConfigurer() 
      ) */.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
  }

security5 + spring boot , 实现的 WebSecurityConfigurerAdapter 接口,配置文件不生效

security5 + spring boot , 实现的 WebSecurityConfigurerAdapter 接口,配置文件不生效

高春辉、王春生、朱峰:关于开源创业的 15 件小事

package com.chenxi.config.security;

import com.chenxi.code.sys.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration
@EnableWebSecurity
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired(required = false)
    PasswordEncoder passwordEncoder;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        String password = passwordEncoder.encode("123456");

        System.out.println("password======"+password);
        auth.inMemoryAuthentication().withUser("user").password(password).roles("user").and();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/**").permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .csrf().disable();
    }
}

Spring Security 3.2.1具有不同WebSecurityConfigurerAdapters的多个登录表单

Spring Security 3.2.1具有不同WebSecurityConfigurerAdapters的多个登录表单

我正在将Spring Security 3.2.1.RELEASE与Spring MVC 4.0.4.RELEASE一起使用

我正在尝试为将具有两个不同的登录条目页面的Web应用程序设置Spring Security。我需要页面是不同的,因为它们的样式和访问方式会有所不同。

第一个登录页面面向管理员用户,并保护管理页面/ admin / **

第二个登录页面适用于客户用户,并保护客户页面/ customer / **。

我尝试设置WebSecurityConfigurerAdapter的两个子类来配置单个HttpSecurity对象。

CustomerFormLoginWebSecurity可以保护客户页面,并在未经授权的情况下重定向到客户登录页面。如果未授权,则AdminFormLoginWebSecurity可以保护重定向到管理登录页面的管理页面。

不幸的是,似乎只有第一个配置是强制性的。我认为我缺少一些额外的东西来使这两种方法都能正常工作。

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    public void registerGlobalAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("customer").password("password").roles("CUSTOMER").and()
                .withUser("admin").password("password").roles("ADMIN");
    }

    @Configuration
    @Order(1)
    public static class CustomerFormLoginWebSecurity extends WebSecurityConfigurerAdapter {

        @Override
        public void configure(WebSecurity web) throws Exception {
            web
                    .ignoring()
                    .antMatchers("/","/signin/**","/error/**","/templates/**","/resources/**","/webjars/**");
        }

        protected void configure(HttpSecurity http) throws Exception {
            http
                    .csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/customer/**").hasRole("CUSTOMER")
                    .and()
                    .formLogin()
                    .loginPage("/customer_signin")
                    .failureUrl("/customer_signin?error=1")
                    .defaultSuccessUrl("/customer/home")
                    .loginProcessingUrl("/j_spring_security_check")
                    .usernameParameter("j_username").passwordParameter("j_password")
                    .and()
                    .logout()
                    .permitAll();

            http.exceptionHandling().accessDeniedPage("/customer_signin");
        }
    }

    @Configuration
    public static class AdminFormLoginWebSecurity extends WebSecurityConfigurerAdapter {
        @Override
        public void configure(WebSecurity web) throws Exception {
            web
                    .ignoring()
                    .antMatchers("/","/webjars/**");
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/admin/**").hasRole("ADMIN")
                    .and()
                    .formLogin()
                    .loginPage("/admin_signin")
                    .failureUrl("/admin_signin?error=1")
                    .defaultSuccessUrl("/admin/home")
                    .loginProcessingUrl("/j_spring_security_check")
                    .usernameParameter("j_username").passwordParameter("j_password")
                    .and()
                    .logout()
                    .permitAll();

            http.exceptionHandling().accessDeniedPage("/admin_signin");
        }
    }

}

Spring Security 4自定义登录j_spring_security_check返回http 302

Spring Security 4自定义登录j_spring_security_check返回http 302

我在这里问了有关最新的Spring框架和基于代码的配置的问题

initializer

public class AppInitializer extends        AbstractAnnotationConfigDispatcherServletInitializer {    @Override    protected Class<?>[] getRootConfigClasses() {        return new Class[] { SecurityConfig.class };    }    @Override    protected Class<?>[] getServletConfigClasses() {        return new Class[] { MvcConfig.class };    }    @Override    protected String[] getServletMappings() {        return new String[] { "/" };    }}

MVC config

    @EnableWebMvc    @ComponentScan({ "com.appname.controller" })    public class MvcConfig extends WebMvcConfigurerAdapter {        @Bean        public InternalResourceViewResolver viewResolver() {            InternalResourceViewResolver resolver = new InternalResourceViewResolver();            resolver.setPrefix("/WEB-INF/jsp/");            resolver.setSuffix(".jsp");            return resolver;        }@Override    public void addResourceHandlers(ResourceHandlerRegistry registry) {        registry.addResourceHandler("/res/**").addResourceLocations("/res/");    }    }

security config

@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)public class SecurityConfig extends WebSecurityConfigurerAdapter {    private CustomUserDetailsService customUserDetailsService;public SecurityConfig() {    customUserDetailsService = new CustomUserDetailsService();}@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth)        throws Exception {    auth.inMemoryAuthentication().withUser("user").password("password")            .roles("USER");    auth.userDetailsService(customUserDetailsService);}    @Override    protected void configure(HttpSecurity http) throws Exception {        http.authorizeRequests()            .antMatchers("/res/**").permitAll()            .and().authorizeRequests()            .anyRequest().hasRole("USER")            .and().formLogin().loginPage("/account/signin").permitAll()            .and().logout().permitAll();    }}

security initializer

public class SecurityInitializer extends        AbstractSecurityWebApplicationInitializer {}

custom login

public class CustomUserDetailsService implements UserDetailsService {    private AccountRepository accountRepository;    public CustomUserDetailsService() {        this.accountRepository = new AccountRepository();    }    @Override    public UserDetails loadUserByUsername(String email)            throws UsernameNotFoundException {        Account account = accountRepository.getAccountByEmail(email);        if (account == null) {            throw new UsernameNotFoundException("Invalid email/password.");        }        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();        authorities.add(new SimpleGrantedAuthority("USER"));        return new User(account.getEmail(), account.getPassword(), authorities);    }}

但是,现在我有关于自定义登录的新问题。

发布到j_spring_security_check时,我会收到http 302。

我正在请求/,但登录后仍保留在登录页面上。

因为我使用的是Spring Security 4.x版本,并且纯粹基于代码的配置,所以在Internet上找不到更多参考。任何人都可以帮助找出原因。

EDIT

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ''securityConfig'': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:Could not autowire field: private org.springframework.security.core.userdetails.UserDetailsService sg.mathschool.infra.SecurityConfig.userDetailsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.core.userdetails.UserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:{@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=userDetailsService)}

I changed CustomUserDetailsService

@Service("userDetailsService")public class CustomUserDetailsService implements UserDetailsService {    private AccountRepository accountRepository;    public CustomUserDetailsService() {        this.accountRepository = new AccountRepository();    }    @Override    @Transactional(readOnly = true)    public UserDetails loadUserByUsername(String email)            throws UsernameNotFoundException {        Account account = accountRepository.getAccountByEmail(email);        if (account == null) {            throw new UsernameNotFoundException("Invalid email/password.");        }        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();        authorities.add(new SimpleGrantedAuthority("USER"));        return new User(account.getEmail(), account.getPassword(), authorities);    }}

和 security config

@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)public class SecurityConfig extends WebSecurityConfigurerAdapter {    @Autowired    @Qualifier("userDetailsService")    private UserDetailsService userDetailsService;    @Autowired    public void configureGlobal(AuthenticationManagerBuilder auth)            throws Exception {        auth.inMemoryAuthentication().withUser("user").password("password")                .roles("USER");        auth.userDetailsService(userDetailsService).passwordEncoder(                passwordEncoder());    }    @Override    protected void configure(HttpSecurity http) throws Exception {        http.authorizeRequests().antMatchers("/res/**").permitAll()                .antMatchers("/account/**").permitAll().anyRequest()                .hasRole("USER").and().formLogin().loginPage("/account/signin")                .failureUrl("/account/signin?error").usernameParameter("email")                .passwordParameter("password").and().logout()                .logoutSuccessUrl("/account/signin?logout").and().csrf();    }    @Bean    public PasswordEncoder passwordEncoder() {        PasswordEncoder encoder = new BCryptPasswordEncoder();        return encoder;    }}

答案1

小编典典

在Spring Security 4.x中,登录URL已更改为,login而不是 j_spring_security_check,请参阅从Spring Security 3.x迁移至4.x(XML配置)。

<form name=''f''action="login" method=''POST''><input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />    <table>        <tbody>            <tr>                <td>User Name</td>                <td><input type="text" name="username" size="30" /></td>            </tr>            <tr>                <td>Password</td>                <td><input type="password" name="password" size="30" /></td>            </tr>            <tr>                <td></td>                <td><input type="submit" value="login" /></td>            </tr>        </tbody>    </table></form>

关于Spring Security配置-HttpSecurity与WebSecurityspring security 配置的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于org.springframework.security.config.annotation.web.builders.HttpSecurity的实例源码、security5 + spring boot , 实现的 WebSecurityConfigurerAdapter 接口,配置文件不生效、Spring Security 3.2.1具有不同WebSecurityConfigurerAdapters的多个登录表单、Spring Security 4自定义登录j_spring_security_check返回http 302的相关知识,请在本站寻找。

本文标签: