Java Code Examples for org.springframework.security.web.AuthenticationEntryPoint

The following examples show how to use org.springframework.security.web.AuthenticationEntryPoint. 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: nifi-registry   Source File: NiFiRegistrySecurityConfig.java    License: Apache License 2.0 7 votes vote down vote up
private AuthenticationEntryPoint http401AuthenticationEntryPoint() {
    // This gets used for both secured and unsecured configurations. It will be called by Spring Security if a request makes it through the filter chain without being authenticated.
    // For unsecured, this should never be reached because the custom AnonymousAuthenticationFilter should always populate a fully-authenticated anonymous user
    // For secured, this will cause attempt to access any API endpoint (except those explicitly ignored) without providing credentials to return a 401 Unauthorized challenge
    return new AuthenticationEntryPoint() {
        @Override
        public void commence(HttpServletRequest request,
                             HttpServletResponse response,
                             AuthenticationException authenticationException)
                throws IOException, ServletException {

            // return a 401 response
            final int status = HttpServletResponse.SC_UNAUTHORIZED;
            logger.info("Client could not be authenticated due to: {} Returning 401 response.", authenticationException.toString());
            logger.debug("", authenticationException);

            if (!response.isCommitted()) {
                response.setStatus(status);
                response.setContentType("text/plain");
                response.getWriter().println(String.format("%s Contact the system administrator.", authenticationException.getLocalizedMessage()));
            }
        }
    };
}
 
Example 2
/**
 * 未登录,返回401
 * 
 * @return
 */
@Bean
public AuthenticationEntryPoint authenticationEntryPoint() {
	return new AuthenticationEntryPoint() {

		@Override
		public void commence(HttpServletRequest request, HttpServletResponse response,
				AuthenticationException authException) throws IOException, ServletException {
			
			Map<String ,String > rsp =new HashMap<>();  
			
			response.setStatus(HttpStatus.UNAUTHORIZED.value() );
			
			rsp.put("resp_code", HttpStatus.UNAUTHORIZED.value() + "") ;
               rsp.put("resp_msg", authException.getMessage()) ;
               
               response.setContentType("application/json;charset=UTF-8");
   			response.getWriter().write(objectMapper.writeValueAsString(rsp));
   			response.getWriter().flush();
   			response.getWriter().close();
               
		}
	};
}
 
Example 3
@Bean
public AuthenticationEntryPoint authenticationEntryPoint(){
    return (HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) ->{
        Map<String, Object> map = new HashMap<>();
        map.put("code", 401);
        map.put("msg", "非法访问资源,访问此资源需要完全身份验证");
        map.put("path", request.getServletPath());
        map.put("timestamp", System.currentTimeMillis());
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(), map);
        } catch (Exception e) {
            throw new ServletException();
        }
    };
}
 
Example 4
@Bean
public AuthenticationEntryPoint authenticationEntryPoint(){
    return (HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) ->{
        Map<String, Object> map = new HashMap<>();
        map.put("code", 401);
        map.put("msg", "非法访问资源,访问此资源需要完全身份验证");
        map.put("path", request.getServletPath());
        map.put("timestamp", System.currentTimeMillis());
        response.setContentType("application/json");
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(), map);
        } catch (Exception e) {
            throw new ServletException();
        }
    };
}
 
Example 5
Source Project: oauth-boot   Source File: OAuth2AuthorizationServerConfig.java    License: MIT License 6 votes vote down vote up
@Autowired(required = false)
public OAuth2AuthorizationServerConfig(AuthenticationManager authenticationManager,
                                       BootClientDetailsService clientDetailsService,
                                       TokenStore tokenStore, JwtAccessTokenConverter converter,
                                       AuthenticationEntryPoint authenticationEntryPoint,
                                       BootOAuth2WebResponseExceptionTranslator bootWebResponseExceptionTranslator,
                                       PasswordEncoder passwordEncoder, BootUserDetailService userDetailsService) {
    this.authenticationManager = authenticationManager;
    this.clientDetailsService = clientDetailsService;
    this.tokenStore = tokenStore;
    this.converter = converter;
    this.authenticationEntryPoint = authenticationEntryPoint;
    this.bootWebResponseExceptionTranslator = bootWebResponseExceptionTranslator;
    this.passwordEncoder = passwordEncoder;
    this.userDetailsService = userDetailsService;
}
 
Example 6
Source Project: atlas   Source File: AtlasSecurityConfig.java    License: Apache License 2.0 6 votes vote down vote up
public AuthenticationEntryPoint getAuthenticationEntryPoint() throws Exception {
    AuthenticationEntryPoint authenticationEntryPoint;

    if (keycloakEnabled) {
        KeycloakAuthenticationEntryPoint keycloakAuthenticationEntryPoint = new KeycloakAuthenticationEntryPoint(adapterDeploymentContext());
        keycloakAuthenticationEntryPoint.setRealm("atlas.com");
        keycloakAuthenticationEntryPoint.setLoginUri("/login.jsp");
        authenticationEntryPoint = keycloakAuthenticationEntryPoint;
    } else {
        LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPointMap = new LinkedHashMap<>();
        entryPointMap.put(new RequestHeaderRequestMatcher(HeadersUtil.USER_AGENT_KEY, HeadersUtil.USER_AGENT_VALUE), atlasAuthenticationEntryPoint);
        AtlasDelegatingAuthenticationEntryPoint basicAuthenticationEntryPoint = new AtlasDelegatingAuthenticationEntryPoint(entryPointMap);
        authenticationEntryPoint = basicAuthenticationEntryPoint;
    }
    return authenticationEntryPoint;
}
 
Example 7
Source Project: find   Source File: HodSecurity.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("ProhibitedExceptionDeclared")
@Override
protected void configure(final HttpSecurity http) throws Exception {
    final AuthenticationEntryPoint ssoEntryPoint = new SsoAuthenticationEntryPoint(SsoController.SSO_PAGE);

    final SsoAuthenticationFilter<?> ssoAuthenticationFilter = new SsoAuthenticationFilter<>(SsoController.SSO_AUTHENTICATION_URI, EntityType.CombinedSso.INSTANCE);
    ssoAuthenticationFilter.setAuthenticationManager(authenticationManager());

    final LogoutSuccessHandler logoutSuccessHandler = new HodTokenLogoutSuccessHandler(SsoController.SSO_LOGOUT_PAGE, tokenRepository);

    http.regexMatcher("/public(/.*)?|/sso|/authenticate-sso|/api/authentication/.*|/logout")
        .csrf()
            .disable()
        .exceptionHandling()
            .authenticationEntryPoint(ssoEntryPoint)
            .accessDeniedPage(DispatcherServletConfiguration.AUTHENTICATION_ERROR_PATH)
            .and()
        .authorizeRequests()
            .antMatchers(FindController.APP_PATH + "/**").hasRole(FindRole.USER.name())
            .and()
        .logout()
            .logoutSuccessHandler(logoutSuccessHandler)
            .and()
        .addFilterAfter(ssoAuthenticationFilter, AbstractPreAuthenticatedProcessingFilter.class);
}
 
Example 8
Source Project: Spring   Source File: SecurityConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean

    public ExceptionTranslationFilter exceptionTranslationFilter() {
        final AuthenticationEntryPoint loginUrlAuthenticationEntryPoint
                = new LoginUrlAuthenticationEntryPoint("/login.jsp");

        final AccessDeniedHandlerImpl accessDeniedHandlerImpl = new AccessDeniedHandlerImpl();
        accessDeniedHandlerImpl.setErrorPage("/accessDenied.jsp");

        final ExceptionTranslationFilter eTranslationFilter = new ExceptionTranslationFilter(loginUrlAuthenticationEntryPoint);
        eTranslationFilter.setAccessDeniedHandler(accessDeniedHandlerImpl);
        return eTranslationFilter;
    }
 
Example 9
Source Project: pacbot   Source File: ResourceServerConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Inject your custom exception translator into the OAuth2 {@link AuthenticationEntryPoint}.
 *
 * @return AuthenticationEntryPoint
 */
@Bean
public AuthenticationEntryPoint authenticationEntryPoint() {
    final OAuth2AuthenticationEntryPoint entryPoint = new OAuth2AuthenticationEntryPoint();
    entryPoint.setExceptionTranslator(exceptionTranslator());
    return entryPoint;
}
 
Example 10
/**
 * Registers a handler to handle all authentication exceptions.
 *
 * @return The registered authentication entry point.
 */
@Bean
@ConditionalOnClass(name = "org.springframework.security.web.AuthenticationEntryPoint")
public AuthenticationEntryPoint authenticationEntryPoint() {
    return (request, response, exception) -> {
        if (!response.isCommitted()) {
            request.setAttribute(ERROR_ATTRIBUTE, exception);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    };
}
 
Example 11
Source Project: atlas   Source File: AtlasSecurityConfig.java    License: Apache License 2.0 5 votes vote down vote up
public DelegatingAuthenticationEntryPoint getDelegatingAuthenticationEntryPoint() throws Exception {
    LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPointMap = new LinkedHashMap<>();
    entryPointMap.put(new RequestHeaderRequestMatcher(HeadersUtil.USER_AGENT_KEY, HeadersUtil.USER_AGENT_VALUE), atlasAuthenticationEntryPoint);
    DelegatingAuthenticationEntryPoint entryPoint = new DelegatingAuthenticationEntryPoint(entryPointMap);
    entryPoint.setDefaultEntryPoint(getAuthenticationEntryPoint());
    return entryPoint;
}
 
Example 12
Source Project: spring-tsers-auth   Source File: WebSecurityConfig.java    License: Apache License 2.0 5 votes vote down vote up
private static AuthenticationEntryPoint getAuthEntryPoint() {
    return new AuthenticationEntryPoint() {
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied");
        }
    };
}
 
Example 13
Source Project: find   Source File: IdolSecurity.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("ProhibitedExceptionDeclared")
@Override
protected void configure(final HttpSecurity http) throws Exception {
    final LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints = new LinkedHashMap<>();
    entryPoints.put(new AntPathRequestMatcher("/api/**"), new Http403ForbiddenEntryPoint());
    entryPoints.put(AnyRequestMatcher.INSTANCE, new LoginUrlAuthenticationEntryPoint(FindController.DEFAULT_LOGIN_PAGE));
    final AuthenticationEntryPoint authenticationEntryPoint = new DelegatingAuthenticationEntryPoint(entryPoints);

    http
        .csrf()
            .disable()
        .exceptionHandling()
            .authenticationEntryPoint(authenticationEntryPoint)
            .accessDeniedPage("/authentication-error")
            .and()
        .logout()
            .logoutUrl("/logout")
            .logoutSuccessUrl(FindController.DEFAULT_LOGIN_PAGE)
            .and()
        .authorizeRequests()
            .antMatchers(FindController.APP_PATH + "/**").hasAnyRole(FindRole.USER.name())
            .antMatchers(FindController.CONFIG_PATH).hasRole(FindRole.CONFIG.name())
            .antMatchers("/api/public/**").hasRole(FindRole.USER.name())
            .antMatchers("/api/bi/**").hasRole(FindRole.BI.name())
            .antMatchers("/api/config/**").hasRole(FindRole.CONFIG.name())
            .antMatchers("/api/admin/**").hasRole(FindRole.ADMIN.name())
            .antMatchers(FindController.DEFAULT_LOGIN_PAGE).permitAll()
            .antMatchers(FindController.LOGIN_PATH).permitAll()
            .antMatchers("/").permitAll()
            .anyRequest().denyAll()
            .and()
        .headers()
            .defaultsDisabled()
            .frameOptions()
            .sameOrigin();

    idolSecurityCustomizer.customize(http, authenticationManager());
}
 
Example 14
Source Project: incubator-atlas   Source File: AtlasSecurityConfig.java    License: Apache License 2.0 5 votes vote down vote up
public DelegatingAuthenticationEntryPoint getDelegatingAuthenticationEntryPoint() {
    LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPointMap = new LinkedHashMap<>();
    entryPointMap.put(new RequestHeaderRequestMatcher("User-Agent", "Mozilla"), atlasAuthenticationEntryPoint);
    DelegatingAuthenticationEntryPoint entryPoint = new DelegatingAuthenticationEntryPoint(entryPointMap);
    entryPoint.setDefaultEntryPoint(getAuthenticationEntryPoint());
    return entryPoint;
}
 
Example 15
/**
 * Create a RestBasicAuthenticationEntryPoint bean. Overrides the default BasicAuthenticationEntryPoint behavior
 * to support Basic Authentication for REST API interaction.
 * 
 * @return An AuthenticationEntryPoint instance.
 */
@Bean
public AuthenticationEntryPoint apiAuthenticationEntryPoint() {
    final RestBasicAuthenticationEntryPoint entryPoint = new RestBasicAuthenticationEntryPoint();
    entryPoint.setRealmName("api realm");
    return entryPoint;
}
 
Example 16
/**
 * Create a RestBasicAuthenticationEntryPoint bean. Overrides the default BasicAuthenticationEntryPoint behavior
 * to support Basic Authentication for REST API interaction.
 * 
 * @return An AuthenticationEntryPoint instance.
 */
@Bean
public AuthenticationEntryPoint actuatorAuthenticationEntryPoint() {
    final RestBasicAuthenticationEntryPoint entryPoint = new RestBasicAuthenticationEntryPoint();
    entryPoint.setRealmName("actuator realm");
    return entryPoint;
}
 
Example 17
Source Project: syncope   Source File: JWTAuthenticationFilter.java    License: Apache License 2.0 5 votes vote down vote up
public JWTAuthenticationFilter(
        final AuthenticationManager authenticationManager,
        final AuthenticationEntryPoint authenticationEntryPoint,
        final SyncopeAuthenticationDetailsSource authenticationDetailsSource,
        final AuthDataAccessor dataAccessor,
        final DefaultCredentialChecker credentialChecker) {

    super(authenticationManager);
    this.authenticationEntryPoint = authenticationEntryPoint;
    this.authenticationDetailsSource = authenticationDetailsSource;
    this.dataAccessor = dataAccessor;
    this.credentialChecker = credentialChecker;
}
 
Example 18
Source Project: devicehive-java-server   Source File: WebSecurityConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public AuthenticationEntryPoint unauthorizedEntryPoint() {
    return (request, response, authException) -> {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getOutputStream().println(
                gson.toJson(new ErrorResponse(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage())));
    };
}
 
Example 19
Source Project: devicehive-java-server   Source File: WebSecurityConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public AuthenticationEntryPoint unauthorizedEntryPoint() {
    return (request, response, authException) -> {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getOutputStream().println(
                gson.toJson(new ErrorResponse(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage())));
    };
}
 
Example 20
Source Project: devicehive-java-server   Source File: WebSecurityConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public AuthenticationEntryPoint unauthorizedEntryPoint() {
    return (request, response, authException) -> {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getOutputStream().println(
                gson.toJson(new ErrorResponse(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage())));
    };
}
 
Example 21
Source Project: we-cmdb   Source File: SpringWebConfig.java    License: Apache License 2.0 4 votes vote down vote up
public AuthenticationEntryPoint casAuthenticationEntryPoint() {
    CasAuthenticationEntryPoint point = new CasAuthenticationEntryPoint();
    point.setLoginUrl(securityProperties.getCasServerUrl() + "/login");
    point.setServiceProperties(serviceProperties());
    return point;
}
 
Example 22
public ApiBootWebSecurityAutoConfiguration(ApiBootSecurityProperties apiBootSecurityProperties, AccessDeniedHandler accessDeniedHandler, AuthenticationEntryPoint authenticationEntryPoint) {
    this.apiBootSecurityProperties = apiBootSecurityProperties;
    this.accessDeniedHandler = accessDeniedHandler;
    this.authenticationEntryPoint = authenticationEntryPoint;
}
 
Example 23
@Override
protected AuthenticationEntryPoint getAuthenticationEntryPoint() {
    return ObjectUtils.isEmpty(this.authenticationEntryPoint) ? new ApiBootDefaultAuthenticationEntryPoint() : this.authenticationEntryPoint;
}
 
Example 24
public ApiBootWebSecurityMemoryAutoConfiguration(ApiBootSecurityProperties apiBootSecurityProperties, ObjectProvider<AccessDeniedHandler> accessDeniedHandler, ObjectProvider<AuthenticationEntryPoint> authenticationEntryPoint) {
    super(apiBootSecurityProperties, accessDeniedHandler.getIfAvailable(), authenticationEntryPoint.getIfAvailable());
}
 
Example 25
public ApiBootWebSecurityJdbcAutoConfiguration(ApiBootSecurityProperties apiBootSecurityProperties, ObjectProvider<AccessDeniedHandler> accessDeniedHandler, ObjectProvider<AuthenticationEntryPoint> authenticationEntryPoint) {
    super(apiBootSecurityProperties, accessDeniedHandler.getIfAvailable(), authenticationEntryPoint.getIfAvailable());
}
 
Example 26
Source Project: spring-boot-security-rest   Source File: WebSecurityConfig.java    License: MIT License 4 votes vote down vote up
@Bean
public AuthenticationEntryPoint unauthorizedEntryPoint() {
	return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
			"Unauthorized");
}
 
Example 27
public JwtSsoBasedAuthenticationFilter(AuthenticationManager authenticationManager,
        AuthenticationEntryPoint authenticationEntryPoint) {
    super(authenticationManager, authenticationEntryPoint);
}
 
Example 28
Source Project: sbp   Source File: SecurityConfig.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
public AuthenticationEntryPoint restAuthenticationEntryPoint() {
    return (request, response, authException) ->
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
 
Example 29
public ApiBootWebSecurityAutoConfiguration(ApiBootSecurityProperties apiBootSecurityProperties, AccessDeniedHandler accessDeniedHandler, AuthenticationEntryPoint authenticationEntryPoint) {
    this.apiBootSecurityProperties = apiBootSecurityProperties;
    this.accessDeniedHandler = accessDeniedHandler;
    this.authenticationEntryPoint = authenticationEntryPoint;
}
 
Example 30
@Override
protected AuthenticationEntryPoint getAuthenticationEntryPoint() {
    return ObjectUtils.isEmpty(this.authenticationEntryPoint) ? new ApiBootDefaultAuthenticationEntryPoint() : this.authenticationEntryPoint;
}