org.springframework.security.web.AuthenticationEntryPoint Java Examples

The following examples show how to use org.springframework.security.web.AuthenticationEntryPoint. 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: ResourceServerConfiguration.java    From spring-security with Apache License 2.0 8 votes vote down vote up
@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 #2
Source File: NiFiRegistrySecurityConfig.java    From nifi-registry with 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 #3
Source File: AtlasSecurityConfig.java    From atlas with 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 #4
Source File: OAuth2AuthorizationServerConfig.java    From oauth-boot with 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 #5
Source File: HodSecurity.java    From find with 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 #6
Source File: SecurityHandlerConfig.java    From open-capacity-platform with Apache License 2.0 6 votes vote down vote up
/**
 * 未登录,返回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 #7
Source File: ResourceServerConfiguration.java    From spring-security with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: SecurityConfiguration.java    From skeleton-ws-spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #9
Source File: AtlasSecurityConfig.java    From atlas with 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 #10
Source File: WebSecurityConfig.java    From spring-tsers-auth with 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 #11
Source File: IdolSecurity.java    From find with 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 #12
Source File: ServletSecurityErrorsAutoConfiguration.java    From errors-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #13
Source File: ResourceServerConfig.java    From pacbot with 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 #14
Source File: SecurityConfig.java    From Spring with 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 #15
Source File: AtlasSecurityConfig.java    From incubator-atlas with 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 #16
Source File: SecurityConfiguration.java    From skeleton-ws-spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 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 File: WebSecurityConfig.java    From devicehive-java-server with 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 #18
Source File: JWTAuthenticationFilter.java    From syncope with 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 #19
Source File: WebSecurityConfig.java    From devicehive-java-server with 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 File: WebSecurityConfig.java    From devicehive-java-server with 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 File: WebSecurityConfigJWT.java    From quartz-manager with Apache License 2.0 4 votes vote down vote up
@Bean
public AuthenticationEntryPoint restAuthEntryPoint() {
  return new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED);
}
 
Example #22
Source File: AtlasDelegatingAuthenticationEntryPoint.java    From atlas with Apache License 2.0 4 votes vote down vote up
public AtlasDelegatingAuthenticationEntryPoint(LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints) {
    super(entryPoints);
    if (LOG.isDebugEnabled()) {
        LOG.info("AtlasDelegatingAuthenticationEntryPoint-AjaxAwareAuthenticationEntryPoint(): constructor");
    }
}
 
Example #23
Source File: JwtAuthenticationTokenFilter.java    From jersey-jwt-springsecurity with MIT License 4 votes vote down vote up
public JwtAuthenticationTokenFilter(AuthenticationManager authenticationManager,
                                    AuthenticationEntryPoint authenticationEntryPoint) {
    this.authenticationManager = authenticationManager;
    this.authenticationEntryPoint = authenticationEntryPoint;
}
 
Example #24
Source File: OpenApiSecurityConfigurer.java    From spring-backend-boilerplate with Apache License 2.0 4 votes vote down vote up
@Bean
public AuthenticationEntryPoint authenticationEntryPointImpl() {
    return new AuthenticationEntryPointRestImpl();
}
 
Example #25
Source File: BaseSecurityConfig.java    From spring-boot-doma2-sample with Apache License 2.0 4 votes vote down vote up
@Bean
public AuthenticationEntryPoint authenticationEntryPoint() {
    return new DefaultAuthenticationEntryPoint(LOGIN_URL, LOGIN_TIMEOUT_URL);
}
 
Example #26
Source File: KeycloakWebSecurityConfigurerAdapter.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected AuthenticationEntryPoint authenticationEntryPoint() throws Exception {
    return new KeycloakAuthenticationEntryPoint(adapterDeploymentContext());
}
 
Example #27
Source File: MultipleEntryPointsSecurityConfig.java    From tutorials with MIT License 4 votes vote down vote up
@Bean
public AuthenticationEntryPoint loginUrlauthenticationEntryPointWithWarning(){
    return new LoginUrlAuthenticationEntryPoint("/userLoginWithWarning");
}
 
Example #28
Source File: CosmoExceptionLoggerFilter.java    From cosmo with Apache License 2.0 4 votes vote down vote up
public CosmoExceptionLoggerFilter(AuthenticationEntryPoint authenticationEntryPoint) {
    super(authenticationEntryPoint);
}
 
Example #29
Source File: MultipleEntryPointsSecurityConfig.java    From tutorials with MIT License 4 votes vote down vote up
@Bean
public AuthenticationEntryPoint loginUrlauthenticationEntryPoint(){
    return new LoginUrlAuthenticationEntryPoint("/userLogin");
}
 
Example #30
Source File: MultipleEntryPointsSecurityConfig.java    From tutorials with MIT License 4 votes vote down vote up
@Bean
public AuthenticationEntryPoint authenticationEntryPoint(){
    BasicAuthenticationEntryPoint entryPoint = new  BasicAuthenticationEntryPoint();
    entryPoint.setRealmName("admin realm");
    return entryPoint;
}