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

The following examples show how to use org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter. These examples are extracted from open source projects. 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 Project: sctalk   Source File: WebSecurityConfig.java    License: 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
/**
 * 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 3
/**
 * @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 4
@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 5
Source Project: Spring-5.0-Cookbook   Source File: AppSecurityModelC.java    License: 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 6
Source Project: spring-admin-vue   Source File: WebSecurityConfiguration.java    License: 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 7
@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 8
Source Project: spring-security   Source File: WebSecurityConfig.java    License: 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 9
Source Project: spring-security-jwt   Source File: SpringSecurityConfig.java    License: 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 Project: jersey-jwt-springsecurity   Source File: WebSecurityConfig.java    License: 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 11
Source Project: sakai   Source File: SecurityConfig.java    License: 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 12
/**
	 * 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 13
Source Project: docker-crash-course   Source File: JWTWebSecurityConfig.java    License: 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 14
@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 15
Source Project: sakai   Source File: SecurityConfig.java    License: 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 16
Source Project: Spring-5.0-Cookbook   Source File: AppSecurityModelC.java    License: 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 17
Source Project: microservices-spring-boot   Source File: SecurityTokenConfig.java    License: 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 18
@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 19
@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 20
Source Project: black-shop   Source File: WebSecurityConfig.java    License: 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 Project: trivia-microservices   Source File: JsonWebTokenSecurityConfig.java    License: 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 Project: metron   Source File: WebSecurityConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/", "/home", "/login").permitAll()
            .antMatchers("/app/**").permitAll()
            .antMatchers("/vendor/**").permitAll()
            .antMatchers("/fonts/**").permitAll()
            .antMatchers("/assets/images/**").permitAll()
            .antMatchers("/*.js").permitAll()
            .antMatchers("/*.ttf").permitAll()
            .antMatchers("/*.woff2").permitAll()
            .anyRequest().authenticated()
            .and().httpBasic()
            .and()
            .logout()
            .logoutUrl("/api/v1/logout")
            .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
            .invalidateHttpSession(true)
            .deleteCookies("JSESSIONID", knoxCookie);

    List<String> activeProfiles = Arrays.asList(environment.getActiveProfiles());
    if (activeProfiles.contains(MetronRestConstants.CSRF_ENABLE_PROFILE)) {
        http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    } else {
        http.csrf().disable();
    }
    if (activeProfiles.contains(MetronRestConstants.KNOX_PROFILE)) {
      http.addFilterAt(new KnoxSSOAuthenticationFilter(userSearchBase, knoxKeyFile, knoxKeyString,
              knoxCookie, ldapTemplate), UsernamePasswordAuthenticationFilter.class);
    }
}
 
Example 23
Source Project: MovieApp   Source File: SecurityConfig.java    License: MIT License 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .cors()
                .and()
            .csrf()
                .disable()
            .exceptionHandling()
                .authenticationEntryPoint(unauthorizedHandler)
                .and()
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
            .authorizeRequests()
                .antMatchers("/",
                        "/favicon.ico",
                        "/**/*.png",
                        "/**/*.gif",
                        "/**/*.svg",
                        "/**/*.jpg",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js")
                        .permitAll()
                .anyRequest()
                        .authenticated();

    // Add our custom JWT security filter
    http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
 
Example 24
Source Project: tutorials   Source File: SecurityConfiguration.java    License: MIT License 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .csrf()
        .disable()
        .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
        .exceptionHandling()
        .authenticationEntryPoint(problemSupport)
        .accessDeniedHandler(problemSupport)
    .and()
        .headers()
        .frameOptions()
        .disable()
    .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()
        .authorizeRequests()
        .antMatchers("/api/books/purchase/**").authenticated()
        .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/**").authenticated()
        .antMatchers("/management/health").permitAll()
        .antMatchers("/management/info").permitAll()
        .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
    .and()
        .apply(securityConfigurerAdapter());

}
 
Example 25
Source Project: tutorials   Source File: UaaConfiguration.java    License: MIT License 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .exceptionHandling()
        .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
    .and()
        .csrf()
        .disable()
        .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
        .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/**").authenticated()
        .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);
}
 
Example 26
Source Project: xmall   Source File: SecurityConfig.java    License: MIT License 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 27
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
        .exceptionHandling()
        .authenticationEntryPoint(problemSupport)
        .accessDeniedHandler(problemSupport)
    .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("/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());

}
 
Example 28
Source Project: iotplatform   Source File: IoTPSecurityConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
  http.headers().cacheControl().disable().frameOptions().disable().and().cors().and().csrf().disable()
      .exceptionHandling().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
      .authorizeRequests().antMatchers(WEBJARS_ENTRY_POINT).permitAll() // Webjars
      .antMatchers(DEVICE_API_ENTRY_POINT).permitAll() // Device HTTP
                                                       // Transport API
      .antMatchers(FORM_BASED_LOGIN_ENTRY_POINT).permitAll() // Login
                                                             // end-point
      .antMatchers(PUBLIC_LOGIN_ENTRY_POINT).permitAll() // Public login
                                                         // end-point
      .antMatchers(TOKEN_REFRESH_ENTRY_POINT).permitAll() // Token refresh
                                                          // end-point
      .antMatchers(NON_TOKEN_BASED_AUTH_ENTRY_POINTS).permitAll() // static
                                                                  // resources,
                                                                  // user
                                                                  // activation
                                                                  // and
                                                                  // password
                                                                  // reset
                                                                  // end-points
      .and().authorizeRequests().antMatchers(WS_TOKEN_BASED_AUTH_ENTRY_POINT).authenticated() // Protected
                                                                                              // WebSocket
                                                                                              // API
                                                                                              // End-points
      .antMatchers(TOKEN_BASED_AUTH_ENTRY_POINT).authenticated() // Protected
                                                                 // API
                                                                 // End-points
      .and().exceptionHandling().accessDeniedHandler(restAccessDeniedHandler).and()
      .addFilterBefore(buildRestLoginProcessingFilter(), UsernamePasswordAuthenticationFilter.class)
      .addFilterBefore(buildRestPublicLoginProcessingFilter(), UsernamePasswordAuthenticationFilter.class)
      .addFilterBefore(buildJwtTokenAuthenticationProcessingFilter(), UsernamePasswordAuthenticationFilter.class)
      .addFilterBefore(buildRefreshTokenProcessingFilter(), UsernamePasswordAuthenticationFilter.class)
      .addFilterBefore(buildWsJwtTokenAuthenticationProcessingFilter(), UsernamePasswordAuthenticationFilter.class);
}
 
Example 29
@Override
protected void configure(HttpSecurity http) throws Exception {

	// 搜寻匿名标记 url: @AnonymousAccess
	Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = applicationContext.getBean(RequestMappingHandlerMapping.class).getHandlerMethods();
	// 获取匿名标记
	Map<String, Set<String>> anonymousUrls = getAnonymousUrl(handlerMethodMap);

	http.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
		.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint())
		.and()
		.csrf()
		.disable()
		.headers()
		.frameOptions()
		.disable()
		.and()
		.sessionManagement()
		.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
		.and()
		.authorizeRequests()
		// 自定义匿名访问所有url放行:允许匿名和带Token访问,细腻化到每个 Request 类型
		// GET
		.antMatchers(HttpMethod.GET, anonymousUrls.get(RequestMethodEnum.GET.getType()).toArray(new String[0])).permitAll()
		// POST
		.antMatchers(HttpMethod.POST, anonymousUrls.get(RequestMethodEnum.POST.getType()).toArray(new String[0])).permitAll()
		// PUT
		.antMatchers(HttpMethod.PUT, anonymousUrls.get(RequestMethodEnum.PUT.getType()).toArray(new String[0])).permitAll()
		// PATCH
		.antMatchers(HttpMethod.PATCH, anonymousUrls.get(RequestMethodEnum.PATCH.getType()).toArray(new String[0])).permitAll()
		// DELETE
		.antMatchers(HttpMethod.DELETE, anonymousUrls.get(RequestMethodEnum.DELETE.getType()).toArray(new String[0])).permitAll()
		// 所有类型的接口都放行
		.antMatchers(anonymousUrls.get(RequestMethodEnum.ALL.getType()).toArray(new String[0])).permitAll()
		.antMatchers(ArrayUtil.toArray(applicationProperties.getSecurity().getAuthorizePermitAll(), String.class)).permitAll()
		.antMatchers(ArrayUtil.toArray(applicationProperties.getSecurity().getAuthorize(), String.class)).authenticated()
		.and()
		.apply(securityConfigurerAdapter());

}
 
Example 30
Source Project: Spring-5.0-Cookbook   Source File: AppSecurityModelC.java    License: MIT License 5 votes vote down vote up
@Bean
public UsernamePasswordAuthenticationFilter appAuthenticationFilter(AuthenticationManager authMgr) {
 AppAuthenticationFilter filter = new AppAuthenticationFilter();
 filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login.html", "POST") );
 filter.setAuthenticationManager(authMgr);
 return filter;
}