org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter Java Examples

The following examples show how to use org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebSecurityConfig.java    From sctalk with Apache License 2.0 7 votes vote down vote up
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
        .csrf().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .antMatchers("/login").permitAll()
            .antMatchers("/","/admin/").permitAll()
            .antMatchers("/admin/**","/**/favicon.ico", "/webjars/**").permitAll()
            .antMatchers("/users/login").permitAll()
            .antMatchers("/users/**").authenticated()
            .anyRequest().authenticated()
        .and()
            .headers().cacheControl();
    httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    httpSecurity.exceptionHandling().authenticationEntryPoint(entryPointUnauthorizedHandler).accessDeniedHandler(restAccessDeniedHandler);

}
 
Example #2
Source File: SecurityConfig.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            .csrf().disable() // we don't need CSRF because our token is invulnerable
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests().antMatchers(
                    "/",
                    "/index",
                    "/favicon.ico",
                    "/*.html",
                    "/**/*.html",
                    "/**/*.css",
                    "/**/*.js"
            ).permitAll()
            .anyRequest().authenticated();

    // Custom JWT based security filter
    httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
    // disable page caching
    httpSecurity.headers().cacheControl();
}
 
Example #3
Source File: WebSecurityConfig.java    From spring-security with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
    http
            .cors()
            .and().csrf().disable();//开启跨域
    http
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
            /*匿名请求:不需要进行登录拦截的url*/
            .authorizeRequests()
                .antMatchers("/getVerifyCode", "/auth/**").permitAll()
                .anyRequest().authenticated()//其他的路径都是登录后才可访问
                .and()
            .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);
     http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
     http.headers().cacheControl();
}
 
Example #4
Source File: SecurityConfig.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            .csrf().disable() // we don't need CSRF because our token is invulnerable
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests().antMatchers(
                    "/",
                    "/index",
                    "/favicon.ico",
                    "/*.html",
                    "/**/*.html",
                    "/**/*.css",
                    "/**/*.js"
            ).permitAll()
            .anyRequest().authenticated();

    // Custom JWT based security filter
    httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
    // disable page caching
    httpSecurity.headers().cacheControl();
}
 
Example #5
Source File: WebSecurityConfiguration.java    From spring-security-jwt-csrf with MIT License 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .cors()
        .and()
            .csrf()
            .ignoringAntMatchers("/login")
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
        .and()
            .authorizeRequests()
            .antMatchers("/onlyforadmin/**").hasAuthority("ADMIN")
            .antMatchers("/secured/**").hasAnyAuthority("USER", "ADMIN")
            .antMatchers("/**").permitAll()
        .and()
            .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class)
            .addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
 
Example #6
Source File: JWTWebSecurityConfig.java    From docker-crash-course with MIT License 6 votes vote down vote up
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
        .csrf().disable()
        .exceptionHandling().authenticationEntryPoint(jwtUnAuthorizedResponseAuthenticationEntryPoint).and()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
        .authorizeRequests()
        .anyRequest().authenticated();

   httpSecurity
        .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    
    httpSecurity
        .headers()
        .frameOptions().sameOrigin()  //H2 Console Needs this setting
        .cacheControl(); //disable caching
}
 
Example #7
Source File: AppSecurityModelC.java    From Spring-5.0-Cookbook with MIT License 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	 
        http
          .anonymous().authorities("ROLE_ANONYMOUS")
          .and()
          .authorizeRequests()
          .antMatchers("/login**", "/after**").permitAll()
          .antMatchers("/deptanon.html").anonymous()
          .anyRequest().authenticated()       
          .and()
          .formLogin()
          .loginPage("/login.html")
          .defaultSuccessUrl("/deptform.html")
          .failureHandler(customFailureHandler)
          .successHandler(customSuccessHandler)
          .and()
          .addFilterBefore(appAnonAuthFilter(), UsernamePasswordAuthenticationFilter.class)
          .addFilter(appAuthenticationFilter(authenticationManager()))
          .logout().logoutUrl("/logout.html")
          .logoutSuccessHandler(customLogoutHandler)
          .and().exceptionHandling().authenticationEntryPoint(setAuthPoint());
        
        http.csrf().disable();
  }
 
Example #8
Source File: SmsCodeAuthenticationSecurityConfig.java    From paascloud-master with Apache License 2.0 6 votes vote down vote up
/**
	 * Configure.
	 *
	 * @param http the http
	 */
	@Override
	public void configure(HttpSecurity http) {

		SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
		smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
		smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(pcAuthenticationSuccessHandler);
		smsCodeAuthenticationFilter.setAuthenticationFailureHandler(pcAuthenticationFailureHandler);
		String key = UUID.randomUUID().toString();
		smsCodeAuthenticationFilter.setRememberMeServices(new PersistentTokenBasedRememberMeServices(key, userDetailsService, persistentTokenRepository));

		SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
		smsCodeAuthenticationProvider.setUserDetailsService(userDetailsService);

		http.authenticationProvider(smsCodeAuthenticationProvider)
				.addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

//		

	}
 
Example #9
Source File: SpringSecurityConfig.java    From spring-security-jwt with MIT License 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .exceptionHandling().and()
            .anonymous().and()
            .servletApi().and()
            .headers().cacheControl().and()
            .authorizeRequests()

            // Allow anonymous resource requests
            .antMatchers("/").permitAll()
            .antMatchers("/favicon.ico").permitAll()
            .antMatchers("/**/*.html").permitAll()
            .antMatchers("/**/*.css").permitAll()
            .antMatchers("/**/*.js").permitAll()

            // Allow anonymous logins
            .antMatchers("/auth/**").permitAll()

            // All other request need to be authenticated
            .anyRequest().authenticated().and()

            // Custom Token based authentication based on the header previously given to the client
            .addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService), UsernamePasswordAuthenticationFilter.class);
}
 
Example #10
Source File: SecurityTokenConfig.java    From microservices-spring-boot with MIT License 6 votes vote down vote up
@Override
 	protected void configure(HttpSecurity http) throws Exception {
   	   http
	.csrf().disable()
	    // make sure we use stateless session; session won't be used to store user's state.
 	    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) 	
	.and()
	    // handle an authorized attempts 
	    .exceptionHandling().authenticationEntryPoint((req, rsp, e) -> rsp.sendError(HttpServletResponse.SC_UNAUTHORIZED)) 	
	.and()
	   // Add a filter to validate the tokens with every request
	   .addFilterAfter(new JwtTokenAuthenticationFilter(jwtConfig), UsernamePasswordAuthenticationFilter.class)
	// authorization requests config
	.authorizeRequests()
	   // allow all who are accessing "auth" service
	   .antMatchers(HttpMethod.POST, jwtConfig.getUri()).permitAll()  
	   // must be an admin if trying to access admin area (authentication is also required here)
	   .antMatchers("/gallery" + "/admin/**").hasRole("ADMIN")
	   // Any other request must be authenticated
	   .anyRequest().authenticated(); 
}
 
Example #11
Source File: JWTWebSecurityConfig.java    From pcf-crash-course-with-spring-boot with MIT License 6 votes vote down vote up
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
        .csrf().disable()
        .exceptionHandling().authenticationEntryPoint(jwtUnAuthorizedResponseAuthenticationEntryPoint).and()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
        .authorizeRequests()
        .anyRequest().authenticated();

   httpSecurity
        .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    
    httpSecurity
        .headers()
        .frameOptions().sameOrigin()  //H2 Console Needs this setting
        .cacheControl(); //disable caching
}
 
Example #12
Source File: WebSecurityConfiguration.java    From spring-admin-vue with Apache License 2.0 6 votes vote down vote up
/**
 * @describe spring Security配置
 * @date 2018/10/29
 * @author Wang Chen Chen
 */
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.cors().and().csrf().disable()
            //未授权处理
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and().authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .antMatchers("/auth/**", "/actuator/**").permitAll()
            .antMatchers(
                    "/v2/api-docs",
                    "/doc.html",
                    "/configuration/ui",
                    "/swagger-resources",
                    "/configuration/security",
                    "/webjars/**",
                    "/swagger-resources/configuration/ui",
                    "/swagge‌​r-ui.html"
            )
            .permitAll().anyRequest().authenticated();
    httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    httpSecurity.headers().cacheControl();
}
 
Example #13
Source File: WebSecurityConfigration.java    From Taroco with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry =
            http
                    // 默认的用户名密码认证器
                    .authenticationProvider(daoAuthenticationProvider())
                    .apply(mobileTokenAuthenticationSecurityConfigration)
                    .and()
                    .apply(smsCodeAuthenticationSecurityConfigration)
                    .and()
                    .addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                    .formLogin().loginPage("/").permitAll()
                    .loginProcessingUrl("/login").permitAll()
                    .and().logout().logoutUrl("/logout").permitAll().logoutSuccessHandler(logoutSuccessHandler)
                    // 异常处理filter: ExceptionTranslationFilter
                    .and().exceptionHandling()
                    // 匿名用户访问无权限资源时的异常
                    //.authenticationEntryPoint(exceptionEntryPoint)
                    // 认证过的用户访问无权限资源时的异常
                    .accessDeniedHandler(accessDeniedHandler)
                    // 开启RememberMe
                    .and().rememberMe().key(RM_KEY).rememberMeServices(rememberMeServices())
                    .and().authorizeRequests();

    final List<String> urlPermitAll = oauth2Properties.getUrlPermitAll();
    urlPermitAll.forEach(url -> registry.antMatchers(url).permitAll());
    registry.anyRequest().authenticated().and().cors().and().csrf().disable();
}
 
Example #14
Source File: AppSecurityModelC.java    From Spring-5.0-Cookbook with MIT License 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	 
        http
          .anonymous().authorities("ROLE_ANONYMOUS")
          .and()
          .authorizeRequests()
          .antMatchers("/login**", "/after**").permitAll()
          .antMatchers("/deptanon.html").anonymous()
          .anyRequest().authenticated()       
          .and()
          .formLogin()
          .loginPage("/login.html")
          .defaultSuccessUrl("/deptform.html")
          .failureHandler(customFailureHandler)
          .successHandler(customSuccessHandler)
          .and()
          .addFilterBefore(appAnonAuthFilter(), UsernamePasswordAuthenticationFilter.class)
          .addFilter(appAuthenticationFilter(authenticationManager()))
          .logout().logoutUrl("/logout.html")
          .logoutSuccessHandler(customLogoutHandler)
          .and().exceptionHandling().authenticationEntryPoint(setAuthPoint());
        
        http.csrf().disable();
  }
 
Example #15
Source File: JWTWebSecurityConfig.java    From spring-boot-vuejs-fullstack-examples with MIT License 6 votes vote down vote up
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
        .csrf().disable()
        .exceptionHandling().authenticationEntryPoint(jwtUnAuthorizedResponseAuthenticationEntryPoint).and()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
        .authorizeRequests()
        .anyRequest().authenticated();

   httpSecurity
        .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    
    httpSecurity
        .headers()
        .frameOptions().sameOrigin()  //H2 Console Needs this setting
        .cacheControl(); //disable caching
}
 
Example #16
Source File: WebSecurityConfig.java    From jersey-jwt-springsecurity with MIT License 6 votes vote down vote up
@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);
}
 
Example #17
Source File: DunwuSecurityConfiguration.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable();

    // 授权配置
    http.authorizeRequests()
        // 无需认证的请求路径
        .antMatchers(dunwuSecurityProperties.getPermitUrls()).permitAll()
        // 所有请求都需要认证
        .anyRequest().authenticated();

    http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) // 添加验证码校验过滤器
        .formLogin() // 表单登录
        .loginPage(dunwuSecurityProperties.getLoginPage()) // 登录跳转 URL
        .loginProcessingUrl(dunwuSecurityProperties.getLoginProcessingUrl()) // 处理表单登录 URL
        .successHandler(authenticationSucessHandler) // 处理登录成功
        .failureHandler(authenticationFailureHandler); // 处理登录失败

    http.rememberMe().tokenRepository(persistentTokenRepository()) // 配置
        // 持久化仓库
        .tokenValiditySeconds(3600) // remember 过期时间,单为秒
        .userDetailsService(userDetailsManager); // 处理自动登录逻辑
}
 
Example #18
Source File: DunwuSecurityConfig.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) // 添加验证码校验过滤器
        .formLogin() // 表单登录
        // http.httpBasic() // HTTP Basic
        .loginPage("/unauthorized") // 登录跳转 URL
        .loginProcessingUrl("/login") // 处理表单登录 URL
        .successHandler(authenticationSucessHandler) // 处理登录成功
        .failureHandler(authenticationFailureHandler) // 处理登录失败
        .and().rememberMe().tokenRepository(persistentTokenRepository()) // 配置
        // token
        // 持久化仓库
        .tokenValiditySeconds(3600) // remember 过期时间,单为秒
        .userDetailsService(userDetailsManager) // 处理自动登录逻辑
        .and().authorizeRequests() // 授权配置
        .antMatchers("/unauthorized", "/login.html", "/css/*.css", "/code/image").permitAll() // 无需认证的请求路径
        .anyRequest() // 所有请求
        .authenticated() // 都需要认证
        .and().csrf().disable();
}
 
Example #19
Source File: SecurityConfigurer.java    From uexam with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @param http http
 * @throws Exception exception
 *                   csrf is the from submit get method
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.headers().frameOptions().disable();

    List<String> securityIgnoreUrls = systemConfig.getSecurityIgnoreUrls();
    String[] ignores = new String[securityIgnoreUrls.size()];
    http
            .addFilterAt(authenticationFilter(), UsernamePasswordAuthenticationFilter.class)
            .exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint)
            .and().authenticationProvider(restAuthenticationProvider)
            .authorizeRequests()
            .antMatchers(securityIgnoreUrls.toArray(ignores)).permitAll()
            .antMatchers("/api/admin/**").hasRole(RoleEnum.ADMIN.getName())
            .antMatchers("/api/student/**").hasRole(RoleEnum.STUDENT.getName())
            .anyRequest().permitAll()
            .and().exceptionHandling().accessDeniedHandler(restAccessDeniedHandler)
            .and().formLogin().successHandler(restAuthenticationSuccessHandler).failureHandler(restAuthenticationFailureHandler)
            .and().logout().logoutUrl("/api/user/logout").logoutSuccessHandler(restLogoutSuccessHandler).invalidateHttpSession(true)
            .and().rememberMe().key(CookieConfig.getName()).tokenValiditySeconds(CookieConfig.getInterval()).userDetailsService(formDetailsService)
            .and().csrf().disable()
            .cors();
}
 
Example #20
Source File: WebSecurityConfig.java    From black-shop with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .anyRequest().authenticated().and()
        // custom token authorize exception handler
        .exceptionHandling()
        .authenticationEntryPoint(unauthorizedHandler).and()
        // since we use jwt, session is not necessary
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
        // since we use jwt, csrf is not necessary
        .csrf().disable();
    http.addFilterBefore(new JwtAuthenticationTokenFilter(tokenProvider), UsernamePasswordAuthenticationFilter.class);

    // disable cache
    http.headers().cacheControl();
}
 
Example #21
Source File: JsonWebTokenSecurityConfig.java    From trivia-microservices with MIT License 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	http
			// disable CSRF, http basic, form login
			.csrf().disable() //
			.httpBasic().disable() //
			.formLogin().disable()

			// ReST is stateless, no sessions
			.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) //

			.and()

			// return 403 when not authenticated
			.exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint());

	// Let child classes set up authorization paths
	setupAuthorization(http);

	http.addFilterBefore(jsonWebTokenFilter, UsernamePasswordAuthenticationFilter.class);
}
 
Example #22
Source File: OpenIdAuthenticationSecurityConfig.java    From paascloud-master with Apache License 2.0 6 votes vote down vote up
/**
 * Configure.
 *
 * @param http the http
 */
@Override
public void configure(HttpSecurity http) {

	OpenIdAuthenticationFilter openIdAuthenticationFilter = new OpenIdAuthenticationFilter();
	openIdAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
	openIdAuthenticationFilter.setAuthenticationSuccessHandler(pcAuthenticationSuccessHandler);
	openIdAuthenticationFilter.setAuthenticationFailureHandler(pcAuthenticationFailureHandler);

	OpenIdAuthenticationProvider openIdAuthenticationProvider = new OpenIdAuthenticationProvider();
	openIdAuthenticationProvider.setUserDetailsService(userDetailsService);
	openIdAuthenticationProvider.setUsersConnectionRepository(usersConnectionRepository);

	http.authenticationProvider(openIdAuthenticationProvider)
			.addFilterAfter(openIdAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

}
 
Example #23
Source File: SecurityConfig.java    From mall-learning with Apache License 2.0 5 votes vote down vote up
@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf()// 由于使用的是JWT,我们这里不需要csrf
                .disable()
                .sessionManagement()// 基于token,所以不需要session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, // 允许对于网站静态资源的无授权访问
                        "/",
                        "/*.html",
                        "/favicon.ico",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js",
                        "/swagger-resources/**",
                        "/v2/api-docs/**"
                )
                .permitAll()
                .antMatchers("/admin/login", "/admin/register")// 对登录注册要允许匿名访问
                .permitAll()
                .antMatchers(HttpMethod.OPTIONS)//跨域请求会先进行一次options请求
                .permitAll()
//                .antMatchers("/**")//测试时全部运行访问
//                .permitAll()
                .anyRequest()// 除上面外的所有请求全部需要鉴权认证
                .authenticated();
        // 禁用缓存
        httpSecurity.headers().cacheControl();
        // 添加JWT filter
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //添加自定义未授权和未登录结果返回
        httpSecurity.exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint);
    }
 
Example #24
Source File: SecurityConfig.java    From mall-learning with Apache License 2.0 5 votes vote down vote up
@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf()// 由于使用的是JWT,我们这里不需要csrf
                .disable()
                .sessionManagement()// 基于token,所以不需要session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, // 允许对于网站静态资源的无授权访问
                        "/",
                        "/*.html",
                        "/favicon.ico",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js",
                        "/swagger-resources/**",
                        "/v2/api-docs/**"
                )
                .permitAll()
                .antMatchers("/admin/login", "/admin/register")// 对登录注册要允许匿名访问
                .permitAll()
                .antMatchers("/esProduct/**","/member/readHistory/**")// 搜索及会员浏览记录暂时允许匿名访问
                .permitAll()
                .antMatchers(HttpMethod.OPTIONS)//跨域请求会先进行一次options请求
                .permitAll()
//                .antMatchers("/**")//测试时全部运行访问
//                .permitAll()
                .anyRequest()// 除上面外的所有请求全部需要鉴权认证
                .authenticated();
        // 禁用缓存
        httpSecurity.headers().cacheControl();
        // 添加JWT filter
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //添加自定义未授权和未登录结果返回
        httpSecurity.exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint);
    }
 
Example #25
Source File: SecurityConfig.java    From spring-boot-mongodb-jwt with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(final HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/api/auth").permitAll()
            .antMatchers("/api/signup").permitAll()
            .anyRequest().authenticated()
            .and()
            .addFilterBefore(new AuthenticationTokenFilter(tokenAuthenticationService),
                    UsernamePasswordAuthenticationFilter.class)
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .csrf().disable();
}
 
Example #26
Source File: SmsCodeAuthenticationSecurityConfig.java    From blog-sample with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
    SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
    smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
    smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler);
    smsCodeAuthenticationFilter.setAuthenticationFailureHandler(customAuthenticationFailureHandler);

    SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
    smsCodeAuthenticationProvider.setUserDetailsService(userDetailsService);

    http.authenticationProvider(smsCodeAuthenticationProvider)
            .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
 
Example #27
Source File: WebSecurityConfiguration.java    From cerberus with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressFBWarnings(value = "SPRING_CSRF_PROTECTION_DISABLED")
protected void configure(HttpSecurity http) throws Exception {
  var requestDoesNotRequireAuthMatcher = getDoesRequestsRequireAuthMatcher();
  var dbTokenFilter =
      new DatabaseTokenAuthenticationProcessingFilter(
          authTokenService, requestDoesNotRequireAuthMatcher);

  // Disable CSRF (cross site request forgery)
  http.csrf().disable();

  // No session will be created or used by spring security
  http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

  // Allow requests from the white list to be unauthenticated
  http.authorizeRequests()
      .antMatchers(AUTHENTICATION_NOT_REQUIRED_WHITELIST.toArray(new String[0]))
      .permitAll();

  // Force all other requests to be authenticated
  http.authorizeRequests().anyRequest().authenticated();

  // Add our authentication entry point
  http.exceptionHandling().authenticationEntryPoint(requestWasNotAuthenticatedEntryPoint);

  // Add the auth filters
  http.addFilterBefore(dbTokenFilter, UsernamePasswordAuthenticationFilter.class);
}
 
Example #28
Source File: SecurityConfig.java    From mall-learning with Apache License 2.0 5 votes vote down vote up
@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf()// 由于使用的是JWT,我们这里不需要csrf
                .disable()
                .sessionManagement()// 基于token,所以不需要session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, // 允许对于网站静态资源的无授权访问
                        "/",
                        "/*.html",
                        "/favicon.ico",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js",
                        "/swagger-resources/**",
                        "/v2/api-docs/**"
                )
                .permitAll()
                .antMatchers("/admin/login", "/admin/register")// 对登录注册要允许匿名访问
                .permitAll()
                .antMatchers(HttpMethod.OPTIONS)//跨域请求会先进行一次options请求
                .permitAll()
//                .antMatchers("/**")//测试时全部运行访问
//                .permitAll()
                .anyRequest()// 除上面外的所有请求全部需要鉴权认证
                .authenticated();
        // 禁用缓存
        httpSecurity.headers().cacheControl();
        // 添加JWT filter
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //添加自定义未授权和未登录结果返回
        httpSecurity.exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint);
    }
 
Example #29
Source File: SecurityConfig.java    From macrozheng with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf()// 由于使用的是JWT,我们这里不需要csrf
            .disable()
            .sessionManagement()// 基于token,所以不需要session
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.GET, // 允许对于网站静态资源的无授权访问
                    "/",
                    "/*.html",
                    "/favicon.ico",
                    "/**/*.html",
                    "/**/*.css",
                    "/**/*.js",
                    "/swagger-resources/**",
                    "/v2/api-docs/**"
            )
            .permitAll()
            .antMatchers("/admin/login", "/admin/register")// 对登录注册要允许匿名访问
            .permitAll()
            .antMatchers(HttpMethod.OPTIONS)//跨域请求会先进行一次options请求
            .permitAll()
            .antMatchers("/**")//测试时全部运行访问
            .permitAll()
            .anyRequest()// 除上面外的所有请求全部需要鉴权认证
            .authenticated();
    // 禁用缓存
    httpSecurity.headers().cacheControl();
    // 添加JWT filter
    httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    //添加自定义未授权和未登录结果返回
    httpSecurity.exceptionHandling()
            .accessDeniedHandler(restfulAccessDeniedHandler)
            .authenticationEntryPoint(restAuthenticationEntryPoint);
}
 
Example #30
Source File: WebSecurityConfig.java    From java-tutorial with MIT License 5 votes vote down vote up
/**
 * 设置 HTTP 验证规则
 *
 * @param http HttpSecurity对象
 * @throws Exception
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    // 由于使用的是JWT,关闭csrf验证
    http.csrf().disable()
            // 基于token,所以不需要session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            // 对请求进行认证
            .authorizeRequests()
            // 允许对于网站静态资源的无授权访问
            .antMatchers(
                    HttpMethod.GET,
                    "/",
                    "/*.html",
                    "/v2/api-docs",
                    "/swagger-resources/**",
                    "/swagger-ui.html**",
                    "/favicon.ico",
                    "/**/*.html",
                    "/**/*.css",
                    "/**/*.js"
            ).permitAll()
            // 对于获取token的rest api要允许匿名访问
            .antMatchers("/auth/**").permitAll()
            .antMatchers("/config/**").permitAll()
            // 除上面外的所有请求全部需要鉴权认证
            .anyRequest().authenticated()
            .and()
            .addFilterBefore(new JwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);


    // 禁用缓存
    http.headers().cacheControl();
}