GVKun编程网logo

使用AuthenticationFailureHandler在Spring Security中自定义身份验证失败响应(spring security oauth2自定义认证)

20

在本文中,我们将给您介绍关于使用AuthenticationFailureHandler在SpringSecurity中自定义身份验证失败响应的详细内容,并且为您解答springsecurityoau

在本文中,我们将给您介绍关于使用AuthenticationFailureHandler在Spring Security中自定义身份验证失败响应的详细内容,并且为您解答spring security oauth2自定义认证的相关问题,此外,我们还将为您提供关于@Autowire在Spring Security自定义身份验证提供程序中不起作用、java – 自定义authenticationFilter Spring Security 3.2、org.apache.hadoop.security.authentication.server.AuthenticationHandler的实例源码、org.springframework.security.authentication.AuthenticationDetailsSource的实例源码的知识。

本文目录一览:

使用AuthenticationFailureHandler在Spring Security中自定义身份验证失败响应(spring security oauth2自定义认证)

使用AuthenticationFailureHandler在Spring Security中自定义身份验证失败响应(spring security oauth2自定义认证)

当前,每当用户认证失败时,spring security都会响应:

{"error": "invalid_grant","error_description": "Bad credentials"}

我想使用以下响应代码来增强此响应:

{"responsecode": "XYZ","error": "invalid_grant","error_description": "Bad credentials"}

经过一番摸索之后,看来我需要执行的是实现AuthenticationFailureHandler,我已经开始这样做。但是,无论何时提交无效的登录凭据,似乎都无法访问onAuthenticationFailure方法。我已逐步完成代码,并将日志记录在onAuthenticationFailure方法中以确认未实现。

我的失败处理程序是:

@Componentpublic class SSOAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler{    @Override    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,        AuthenticationException exception) throws IOException, ServletException {        super.onAuthenticationFailure(request, response, exception);        response.addHeader("responsecode", "XYZ");      }}

我的WebSecurityConfigurerAdapter包含:

@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {    @Autowired SSOAuthenticationFailureHandler authenticationFailureHandler;    @Override    protected void configure(HttpSecurity http) throws Exception {        http.csrf().disable();        http.formLogin().failureHandler(authenticationFailureHandler);    }    @Autowired    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {        auth.userDetailsService(service).passwordEncoder(passwordEncoder());        auth.authenticationEventPublisher(defaultAuthenticationEventPublisher());    }    @Bean    public DefaultAuthenticationEventPublisher defaultAuthenticationEventPublisher(){        return new DefaultAuthenticationEventPublisher();    }    @Override    @Bean    public AuthenticationManager authenticationManagerBean() throws Exception {        return super.authenticationManagerBean();    }    @Bean    public SSOAuthenticationFailureHandler authenticationHandlerBean() {        return new SSOAuthenticationFailureHandler();    }    @Bean    public PasswordEncoder passwordEncoder(){        PasswordEncoder encoder = new BCryptPasswordEncoder();        return encoder;    }}

我的问题是:

  1. 这是实现我想要的结果的正确方法吗?(定制spring安全认证响应)
  2. 如果是这样,我在尝试设置身份验证失败处理程序时是否做错了什么(因为错误的登录似乎并没有达到onAuthenticationFailure方法?

答案1

小编典典

你可以通过在configure方法中的HttpSecurity对象上调用.exceptionHandling()来为Spring Security添加异常处理。如果只想处理错误的凭据,则可以忽略.accessDeniedHandler(accessDeniedHandler())。

拒绝访问处理程序可处理你已在方法级别保护应用程序安全的情况,例如使用@ PreAuthorized,@ PostAuthorized和@Secured。

你的安全性配置示例可能像这样

SecurityConfig.java/*    The following two are the classes we''re going to create later on.     You can autowire them into your Security Configuration class.*/@Autowiredprivate CustomAuthenticationEntryPoint unauthorizedHandler;@Autowiredprivate CustomAccessDeniedHandler accessDeniedHandler;    /*  Adds exception handling to you HttpSecurity config object.*/@Overrideprotected void configure(HttpSecurity http) throws Exception {    http.csrf()        .disable()        .exceptionHandling()            .authencationEntryPoint(unauthorizedHandler)  // handles bad credentials            .accessDeniedHandler(accessDeniedHandler);    // You''re using the autowired members above.    http.formLogin().failureHandler(authenticationFailureHandler);}/*  This will be used to create the json we''ll send back to the client from  the CustomAuthenticationEntryPoint class.*/@Beanpublic Jackson2JsonObjectMapper jackson2JsonObjectMapper() {ObjectMapper mapper = new ObjectMapper();    mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);    return new Jackson2JsonObjectMapper(mapper);}  

CustomAuthenticationEntryPoint.java

你可以在其自己的单独文件中创建它。这是入口点处理的无效凭据。在方法内部,我们必须创建自己的JSON并将其写入HttpServletResponse对象。我们将使用在Security Config中创建的Jackson对象映射器bean。

 @Componentpublic class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {    private static final long serialVersionUID = -8970718410437077606L;    @Autowired  // the Jackson object mapper bean we created in the config    private Jackson2JsonObjectMapper jackson2JsonObjectMapper;    @Override    public void commence(HttpServletRequest request,                         HttpServletResponse response,                         AuthenticationException e) throws IOException {        /*           This is a pojo you can create to hold the repsonse code, error, and description.            You can create a POJO to hold whatever information you want to send back.        */         CustomError error = new CustomError(HttpStatus.FORBIDDEN, error, description);        /*          Here we''re going to creat a json strong from the CustomError object we just created.          We set the media type, encoding, and then get the write from the response object and write      our json string to the response.        */        try {            String json = jackson2JsonObjectMapper.toJson(error);            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);            response.setContentType(MediaType.APPLICATION_JSON_VALUE);            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());            response.getWriter().write(json);        } catch (Exception e1) {            e1.printStackTrace();        }    }}

CustomAccessDeniedHandler.java

这将处理授权错误,例如尝试在没有适当特权的情况下访问方法。你可以以与上面相同的方式来实现它,但凭据不良。

@Componentpublic class CustomAccessDeniedHandler implements AccessDeniedHandler {    @Override    public void handle(HttpServletRequest request, HttpServletResponse response,        AccessDeniedException e) throws IOException, ServletException {    // You can create your own repsonse here to handle method level access denied reponses..    // Follow similar method to the bad credentials handler above.    }}

希望这会有所帮助。

@Autowire在Spring Security自定义身份验证提供程序中不起作用

@Autowire在Spring Security自定义身份验证提供程序中不起作用

我们有Spring MVC应用程序。我们正在尝试将Spring安全性集成到其中。

我们已经编写了自定义身份验证提供程序,它将执行身份验证工作。

以下是我的自定义身份验证提供程序的代码。

    public class CustomAuthenticationProvider extends DaoAuthenticationProvider {    @Autowired    private AuthenticationService authenticationService;    @Override    public Authentication authenticate(Authentication authentication) {        CustomAuthenticationToken auth = (CustomAuthenticationToken) authentication;        String username = String.valueOf(auth.getPrincipal());        String password = String.valueOf(auth.getCredentials());        try {            Users user = new User();            user.setUsername(username);            user.setPassword(PasswordUtil.encrypt(password));            user = authenticationService.validateLogin(user);            return auth;        } catch (Exception e) {            throw new BadCredentialsException("Username/Password does not match for " + username);        }    }    @Override    public boolean supports(Class<? extends Object> authentication) {        return (CustomAuthenticationToken.class.isAssignableFrom(authentication));    }}

在这里,我在下一行获取NullpointerException

user = authenticationService.validateLogin(user);

不会在自定义身份验证提供程序中自动连接authenticationService。虽然相同的服务authenticationService在我的MVC控制器中以相同的方式自动接线。

这是因为身份验证提供程序是Spring安全组件吗?

下面是我的web.xml

    <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>        /WEB-INF/spring/myApp-security.xml    </param-value></context-param><servlet>    <servlet-name>myApp</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <init-param>        <param-name>contextConfigLocation</param-name>        <param-value>/WEB-INF/spring/myApp-servlet.xml</param-value>    </init-param>    <load-on-startup>1</load-on-startup></servlet><servlet-mapping>    <servlet-name>myApp</servlet-name>    <url-pattern>/</url-pattern></servlet-mapping><filter>    <filter-name>springSecurityFilterChain</filter-name>    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class></filter><filter-mapping>    <filter-name>springSecurityFilterChain</filter-name>    <url-pattern>/*</url-pattern></filter-mapping><listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>

编辑1:-

我在我的spring安全配置文件中添加了以下几行。

<beans:bean id="customAuthenticationProvider">    <beans:property name="userDetailsService" ref="userDetailsService"/>   </beans:bean>

请帮助如何在Spring安全组件中自动连接服务类?

答案1

小编典典

也许未在根应用程序上下文中启用自动装配后处理器(但在DispatcherServlet的上下文中由于<mvc:annotation-driven>或的影响而启用了<context:component-scan>)。

您可以通过添加<context:annotation-config>到中启用它myApp-security.xml

java – 自定义authenticationFilter Spring Security 3.2

java – 自定义authenticationFilter Spring Security 3.2

对于一个项目,我尝试使用Spring Security 3.2作为基本安全性.因为这个项目已经启动并运行,所以我已经拥有了另一个(自己的)安全层.因此,我制作了一个自定义身份验证提供程序来融化安全层.工作正常,直到我还需要进行自定义匿名身份验证(Spring Security Documentation,chapter 13).

所以我做了一个自定义过滤器并删除了orignal过滤器:

豆子:

和te Java类:

public class SecurityAnonymousAuthenticationFilter extends GenericFilterBean implements InitializingBean {
    public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException,ServletException {
        logger.info("Entering doFilter method");
        //implementation code here
    }

    //other methods
}

问题是请求服务器时不调用doFilter方法.但是调用了init方法afterPropertiesSet()…是否有人理解为什么我的customFilter没有被触发?

附:我确实在web.xml文件中命名了delegatingFilterProxy,所以这不是问题.

最佳答案
由于ANONYMOUS_FILTER是与名称空间相关的过滤器.您必须避免引用特定过滤器psoition的任何名称空间标记:

   

有关进一步参考,请参阅2.3.5:http://static.springsource.org/spring-security/site/docs/3.0.x/reference/ns-config.html中的Spring安全性文档

编辑:并确保保留< anonymous-enabled = false />标签.

编辑2:纠正了我的回答.这种配置应该有效.如果没有,那么我们需要开始查看更大的图片并且您必须发布更多应用,从完整配置开始.

org.apache.hadoop.security.authentication.server.AuthenticationHandler的实例源码

org.apache.hadoop.security.authentication.server.AuthenticationHandler的实例源码

项目:hadoop-oss    文件:DelegationTokenAuthenticationFilter.java   
@Override
public void init(FilterConfig filterConfig) throws servletexception {
  super.init(filterConfig);
  AuthenticationHandler handler = getAuthenticationHandler();
  AbstractDelegationTokenSecretManager dtSecretManager =
      (AbstractDelegationTokenSecretManager) filterConfig.getServletContext().
          getAttribute(DELEGATION_TOKEN_SECRET_MANAGER_ATTR);
  if (dtSecretManager != null && handler
      instanceof DelegationTokenAuthenticationHandler) {
    DelegationTokenAuthenticationHandler dtHandler =
        (DelegationTokenAuthenticationHandler) getAuthenticationHandler();
    dtHandler.setExternalDelegationTokenSecretManager(dtSecretManager);
  }
  if (handler instanceof PseudoAuthenticationHandler ||
      handler instanceof PseudoDelegationTokenAuthenticationHandler) {
    setHandlerAuthMethod(SaslRpcServer.AuthMethod.SIMPLE);
  }
  if (handler instanceof KerberosAuthenticationHandler ||
      handler instanceof KerberosDelegationTokenAuthenticationHandler) {
    setHandlerAuthMethod(SaslRpcServer.AuthMethod.KERBEROS);
  }

  // proxyuser configuration
  Configuration conf = getProxyuserConfiguration(filterConfig);
  ProxyUsers.refreshSuperUserGroupsConfiguration(conf,PROXYUSER_PREFIX);
}
项目:hadoop    文件:DelegationTokenAuthenticationFilter.java   
@Override
public void init(FilterConfig filterConfig) throws servletexception {
  super.init(filterConfig);
  AuthenticationHandler handler = getAuthenticationHandler();
  AbstractDelegationTokenSecretManager dtSecretManager =
      (AbstractDelegationTokenSecretManager) filterConfig.getServletContext().
          getAttribute(DELEGATION_TOKEN_SECRET_MANAGER_ATTR);
  if (dtSecretManager != null && handler
      instanceof DelegationTokenAuthenticationHandler) {
    DelegationTokenAuthenticationHandler dtHandler =
        (DelegationTokenAuthenticationHandler) getAuthenticationHandler();
    dtHandler.setExternalDelegationTokenSecretManager(dtSecretManager);
  }
  if (handler instanceof PseudoAuthenticationHandler ||
      handler instanceof PseudoDelegationTokenAuthenticationHandler) {
    setHandlerAuthMethod(SaslRpcServer.AuthMethod.SIMPLE);
  }
  if (handler instanceof KerberosAuthenticationHandler ||
      handler instanceof KerberosDelegationTokenAuthenticationHandler) {
    setHandlerAuthMethod(SaslRpcServer.AuthMethod.KERBEROS);
  }

  // proxyuser configuration
  Configuration conf = getProxyuserConfiguration(filterConfig);
  ProxyUsers.refreshSuperUserGroupsConfiguration(conf,PROXYUSER_PREFIX);
}
项目:aliyun-oss-hadoop-fs    文件:DelegationTokenAuthenticationFilter.java   
@Override
public void init(FilterConfig filterConfig) throws servletexception {
  super.init(filterConfig);
  AuthenticationHandler handler = getAuthenticationHandler();
  AbstractDelegationTokenSecretManager dtSecretManager =
      (AbstractDelegationTokenSecretManager) filterConfig.getServletContext().
          getAttribute(DELEGATION_TOKEN_SECRET_MANAGER_ATTR);
  if (dtSecretManager != null && handler
      instanceof DelegationTokenAuthenticationHandler) {
    DelegationTokenAuthenticationHandler dtHandler =
        (DelegationTokenAuthenticationHandler) getAuthenticationHandler();
    dtHandler.setExternalDelegationTokenSecretManager(dtSecretManager);
  }
  if (handler instanceof PseudoAuthenticationHandler ||
      handler instanceof PseudoDelegationTokenAuthenticationHandler) {
    setHandlerAuthMethod(SaslRpcServer.AuthMethod.SIMPLE);
  }
  if (handler instanceof KerberosAuthenticationHandler ||
      handler instanceof KerberosDelegationTokenAuthenticationHandler) {
    setHandlerAuthMethod(SaslRpcServer.AuthMethod.KERBEROS);
  }

  // proxyuser configuration
  Configuration conf = getProxyuserConfiguration(filterConfig);
  ProxyUsers.refreshSuperUserGroupsConfiguration(conf,PROXYUSER_PREFIX);
}
项目:big-c    文件:DelegationTokenAuthenticationFilter.java   
@Override
public void init(FilterConfig filterConfig) throws servletexception {
  super.init(filterConfig);
  AuthenticationHandler handler = getAuthenticationHandler();
  AbstractDelegationTokenSecretManager dtSecretManager =
      (AbstractDelegationTokenSecretManager) filterConfig.getServletContext().
          getAttribute(DELEGATION_TOKEN_SECRET_MANAGER_ATTR);
  if (dtSecretManager != null && handler
      instanceof DelegationTokenAuthenticationHandler) {
    DelegationTokenAuthenticationHandler dtHandler =
        (DelegationTokenAuthenticationHandler) getAuthenticationHandler();
    dtHandler.setExternalDelegationTokenSecretManager(dtSecretManager);
  }
  if (handler instanceof PseudoAuthenticationHandler ||
      handler instanceof PseudoDelegationTokenAuthenticationHandler) {
    setHandlerAuthMethod(SaslRpcServer.AuthMethod.SIMPLE);
  }
  if (handler instanceof KerberosAuthenticationHandler ||
      handler instanceof KerberosDelegationTokenAuthenticationHandler) {
    setHandlerAuthMethod(SaslRpcServer.AuthMethod.KERBEROS);
  }

  // proxyuser configuration
  Configuration conf = getProxyuserConfiguration(filterConfig);
  ProxyUsers.refreshSuperUserGroupsConfiguration(conf,PROXYUSER_PREFIX);
}
项目:hadoop-2.6.0-cdh5.4.3    文件:DelegationTokenAuthenticationFilter.java   
@Override
public void init(FilterConfig filterConfig) throws servletexception {
  super.init(filterConfig);
  AuthenticationHandler handler = getAuthenticationHandler();
  AbstractDelegationTokenSecretManager dtSecretManager =
      (AbstractDelegationTokenSecretManager) filterConfig.getServletContext().
          getAttribute(DELEGATION_TOKEN_SECRET_MANAGER_ATTR);
  if (dtSecretManager != null && handler
      instanceof DelegationTokenAuthenticationHandler) {
    DelegationTokenAuthenticationHandler dtHandler =
        (DelegationTokenAuthenticationHandler) getAuthenticationHandler();
    dtHandler.setExternalDelegationTokenSecretManager(dtSecretManager);
  }
  if (handler instanceof PseudoAuthenticationHandler ||
      handler instanceof PseudoDelegationTokenAuthenticationHandler) {
    setHandlerAuthMethod(SaslRpcServer.AuthMethod.SIMPLE);
  }
  if (handler instanceof KerberosAuthenticationHandler ||
      handler instanceof KerberosDelegationTokenAuthenticationHandler) {
    setHandlerAuthMethod(SaslRpcServer.AuthMethod.KERBEROS);
  }

  // proxyuser configuration
  Configuration conf = getProxyuserConfiguration(filterConfig);
  ProxyUsers.refreshSuperUserGroupsConfiguration(conf,PROXYUSER_PREFIX);
}
项目:hadoop-plus    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testManagementOperationErrors(AuthenticationHandler handler)
  throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
    thenReturn(DelegationTokenoperation.GETDELEGATIONTOKEN.toString());
  Mockito.when(request.getmethod()).thenReturn("FOO");
  Assert.assertFalse(handler.managementOperation(null,request,response));
  Mockito.verify(response).sendError(
    Mockito.eq(HttpServletResponse.SC_BAD_REQUEST),Mockito.startsWith("Wrong HTTP method"));

  Mockito.reset(response);
  Mockito.when(request.getmethod()).
    thenReturn(DelegationTokenoperation.GETDELEGATIONTOKEN.getHttpMethod());
  Assert.assertFalse(handler.managementOperation(null,response));
  Mockito.verify(response).sendError(
    Mockito.eq(HttpServletResponse.SC_UNAUTHORIZED),Mockito.contains("requires SPNEGO"));
}
项目:hadoop-plus    文件:TestHttpFSKerberosAuthenticationHandler.java   
@Test
@TestDir
public void testAuthenticate() throws Exception {
  String dir = TestDirHelper.getTestDir().getAbsolutePath();

  Configuration httpfsConf = new Configuration(false);
  HttpFSServerWebApp server =
    new HttpFSServerWebApp(dir,dir,httpfsConf);
  server.setAuthority(new InetSocketAddress(InetAddress.getLocalHost(),14000));
  AuthenticationHandler handler =
    new HttpFSKerberosAuthenticationHandlerForTesting();
  try {
    server.init();
    handler.init(null);

    testValidDelegationToken(handler);
    testInvalidDelegationToken(handler);
  } finally {
    if (handler != null) {
      handler.destroy();
    }
  server.destroy();
  }
}
项目:hadoop-plus    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testValidDelegationToken(AuthenticationHandler handler)
  throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Token<DelegationTokenIdentifier> dToken =
    HttpFSServerWebApp.get().get(DelegationTokenManager.class).createtoken(
      UserGroupinformation.getCurrentUser(),"user");
  Mockito.when(request.getParameter(HttpFSKerberosAuthenticator.DELEGATION_ParaM)).
    thenReturn(dToken.encodetoUrlString());

  AuthenticationToken token = handler.authenticate(request,response);
  Assert.assertEquals(UserGroupinformation.getCurrentUser().getShortUserName(),token.getUserName());
  Assert.assertEquals(0,token.getExpires());
  Assert.assertEquals(HttpFSKerberosAuthenticationHandler.TYPE,token.getType());
  Assert.assertTrue(token.isExpired());
}
项目:hops    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testManagementOperationErrors(AuthenticationHandler handler)
    throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
      thenReturn(DelegationTokenoperation.GETDELEGATIONTOKEN.toString());
  Mockito.when(request.getmethod()).thenReturn("FOO");
  Assert.assertFalse(handler.managementOperation(null,response));
  Mockito.verify(response)
      .sendError(Mockito.eq(HttpServletResponse.SC_BAD_REQUEST),Mockito.startsWith("Wrong HTTP method"));

  Mockito.reset(response);
  Mockito.when(request.getmethod()).
      thenReturn(DelegationTokenoperation.GETDELEGATIONTOKEN.getHttpMethod());
  Assert.assertFalse(handler.managementOperation(null,response));
  Mockito.verify(response)
      .sendError(Mockito.eq(HttpServletResponse.SC_UNAUTHORIZED),Mockito.contains("requires SPNEGO"));
}
项目:hops    文件:TestHttpFSKerberosAuthenticationHandler.java   
@Test
@TestDir
public void testAuthenticate() throws Exception {
  String dir = TestDirHelper.getTestDir().getAbsolutePath();

  Configuration httpfsConf = new Configuration(false);
  HttpFSServerWebApp server =
      new HttpFSServerWebApp(dir,httpfsConf);
  server
      .setAuthority(new InetSocketAddress(InetAddress.getLocalHost(),14000));
  AuthenticationHandler handler =
      new HttpFSKerberosAuthenticationHandlerForTesting();
  try {
    server.init();
    handler.init(null);

    testValidDelegationToken(handler);
    testInvalidDelegationToken(handler);
  } finally {
    if (handler != null) {
      handler.destroy();
    }
    server.destroy();
  }
}
项目:hops    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testValidDelegationToken(AuthenticationHandler handler)
    throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Token<DelegationTokenIdentifier> dToken =
      HttpFSServerWebApp.get().get(DelegationTokenManager.class)
          .createtoken(UserGroupinformation.getCurrentUser(),"user");
  Mockito.when(
      request.getParameter(HttpFSKerberosAuthenticator.DELEGATION_ParaM)).
      thenReturn(dToken.encodetoUrlString());

  AuthenticationToken token = handler.authenticate(request,response);
  Assert
      .assertEquals(UserGroupinformation.getCurrentUser().getShortUserName(),token.getType());
  Assert.assertTrue(token.isExpired());
}
项目:hops    文件:DelegationTokenAuthenticationFilter.java   
@Override
public void init(FilterConfig filterConfig) throws servletexception {
  super.init(filterConfig);
  AuthenticationHandler handler = getAuthenticationHandler();
  AbstractDelegationTokenSecretManager dtSecretManager =
      (AbstractDelegationTokenSecretManager) filterConfig.getServletContext().
          getAttribute(DELEGATION_TOKEN_SECRET_MANAGER_ATTR);
  if (dtSecretManager != null && handler
      instanceof DelegationTokenAuthenticationHandler) {
    DelegationTokenAuthenticationHandler dtHandler =
        (DelegationTokenAuthenticationHandler) getAuthenticationHandler();
    dtHandler.setExternalDelegationTokenSecretManager(dtSecretManager);
  }
  if (handler instanceof PseudoAuthenticationHandler ||
      handler instanceof PseudoDelegationTokenAuthenticationHandler) {
    setHandlerAuthMethod(SaslRpcServer.AuthMethod.SIMPLE);
  }
  if (handler instanceof KerberosAuthenticationHandler ||
      handler instanceof KerberosDelegationTokenAuthenticationHandler) {
    setHandlerAuthMethod(SaslRpcServer.AuthMethod.KERBEROS);
  }

  // proxyuser configuration
  Configuration conf = getProxyuserConfiguration(filterConfig);
  ProxyUsers.refreshSuperUserGroupsConfiguration(conf,PROXYUSER_PREFIX);
}
项目:hadoop-TCP    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testManagementOperationErrors(AuthenticationHandler handler)
  throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
    thenReturn(DelegationTokenoperation.GETDELEGATIONTOKEN.toString());
  Mockito.when(request.getmethod()).thenReturn("FOO");
  Assert.assertFalse(handler.managementOperation(null,Mockito.contains("requires SPNEGO"));
}
项目:hadoop-TCP    文件:TestHttpFSKerberosAuthenticationHandler.java   
@Test
@TestDir
public void testAuthenticate() throws Exception {
  String dir = TestDirHelper.getTestDir().getAbsolutePath();

  Configuration httpfsConf = new Configuration(false);
  HttpFSServerWebApp server =
    new HttpFSServerWebApp(dir,14000));
  AuthenticationHandler handler =
    new HttpFSKerberosAuthenticationHandlerForTesting();
  try {
    server.init();
    handler.init(null);

    testValidDelegationToken(handler);
    testInvalidDelegationToken(handler);
  } finally {
    if (handler != null) {
      handler.destroy();
    }
  server.destroy();
  }
}
项目:hadoop-TCP    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testValidDelegationToken(AuthenticationHandler handler)
  throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Token<DelegationTokenIdentifier> dToken =
    HttpFSServerWebApp.get().get(DelegationTokenManager.class).createtoken(
      UserGroupinformation.getCurrentUser(),token.getType());
  Assert.assertTrue(token.isExpired());
}
项目:hardfs    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testManagementOperationErrors(AuthenticationHandler handler)
  throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
    thenReturn(DelegationTokenoperation.GETDELEGATIONTOKEN.toString());
  Mockito.when(request.getmethod()).thenReturn("FOO");
  Assert.assertFalse(handler.managementOperation(null,Mockito.contains("requires SPNEGO"));
}
项目:hardfs    文件:TestHttpFSKerberosAuthenticationHandler.java   
@Test
@TestDir
public void testAuthenticate() throws Exception {
  String dir = TestDirHelper.getTestDir().getAbsolutePath();

  Configuration httpfsConf = new Configuration(false);
  HttpFSServerWebApp server =
    new HttpFSServerWebApp(dir,14000));
  AuthenticationHandler handler =
    new HttpFSKerberosAuthenticationHandlerForTesting();
  try {
    server.init();
    handler.init(null);

    testValidDelegationToken(handler);
    testInvalidDelegationToken(handler);
  } finally {
    if (handler != null) {
      handler.destroy();
    }
  server.destroy();
  }
}
项目:hardfs    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testValidDelegationToken(AuthenticationHandler handler)
  throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Token<DelegationTokenIdentifier> dToken =
    HttpFSServerWebApp.get().get(DelegationTokenManager.class).createtoken(
      UserGroupinformation.getCurrentUser(),token.getType());
  Assert.assertTrue(token.isExpired());
}
项目:hadoop-on-lustre2    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testManagementOperationErrors(AuthenticationHandler handler)
  throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
    thenReturn(DelegationTokenoperation.GETDELEGATIONTOKEN.toString());
  Mockito.when(request.getmethod()).thenReturn("FOO");
  Assert.assertFalse(handler.managementOperation(null,Mockito.contains("requires SPNEGO"));
}
项目:hadoop-on-lustre2    文件:TestHttpFSKerberosAuthenticationHandler.java   
@Test
@TestDir
public void testAuthenticate() throws Exception {
  String dir = TestDirHelper.getTestDir().getAbsolutePath();

  Configuration httpfsConf = new Configuration(false);
  HttpFSServerWebApp server =
    new HttpFSServerWebApp(dir,14000));
  AuthenticationHandler handler =
    new HttpFSKerberosAuthenticationHandlerForTesting();
  try {
    server.init();
    handler.init(null);

    testValidDelegationToken(handler);
    testInvalidDelegationToken(handler);
  } finally {
    if (handler != null) {
      handler.destroy();
    }
  server.destroy();
  }
}
项目:hadoop-on-lustre2    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testValidDelegationToken(AuthenticationHandler handler)
  throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Token<DelegationTokenIdentifier> dToken =
    HttpFSServerWebApp.get().get(DelegationTokenManager.class).createtoken(
      UserGroupinformation.getCurrentUser(),token.getType());
  Assert.assertTrue(token.isExpired());
}
项目:hadoop-plus    文件:TestHttpFSKerberosAuthenticationHandler.java   
@Test
@TestDir
public void testManagementOperations() throws Exception {
  String dir = TestDirHelper.getTestDir().getAbsolutePath();

  Configuration httpfsConf = new Configuration(false);
  HttpFSServerWebApp server =
    new HttpFSServerWebApp(dir,14000));
  AuthenticationHandler handler =
    new HttpFSKerberosAuthenticationHandlerForTesting();
  try {
    server.init();
    handler.init(null);

    testNonManagementOperation(handler);
    testManagementOperationErrors(handler);
    testGetToken(handler,null);
    testGetToken(handler,"foo");
    testCancelToken(handler);
    testRenewToken(handler);

  } finally {
    if (handler != null) {
      handler.destroy();
    }
  server.destroy();
  }
}
项目:hadoop-plus    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testNonManagementOperation(AuthenticationHandler handler)
  throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
    thenReturn(null);
  Assert.assertTrue(handler.managementOperation(null,null));
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
    thenReturn(HttpFSFileSystem.Operation.CREATE.toString());
  Assert.assertTrue(handler.managementOperation(null,null));
}
项目:hadoop-plus    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testCancelToken(AuthenticationHandler handler)
  throws Exception {
  DelegationTokenoperation op =
    DelegationTokenoperation.CANCELDELEGATIONTOKEN;
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
    thenReturn(op.toString());
  Mockito.when(request.getmethod()).
    thenReturn(op.getHttpMethod());

  Assert.assertFalse(handler.managementOperation(null,Mockito.contains("requires the parameter [token]"));

  Mockito.reset(response);
  Token<DelegationTokenIdentifier> token =
    HttpFSServerWebApp.get().get(DelegationTokenManager.class).createtoken(
      UserGroupinformation.getCurrentUser(),"foo");
  Mockito.when(request.getParameter(HttpFSKerberosAuthenticator.TOKEN_ParaM)).
    thenReturn(token.encodetoUrlString());
  Assert.assertFalse(handler.managementOperation(null,response));
  Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);
  try {
    HttpFSServerWebApp.get().get(DelegationTokenManager.class).verifyToken(token);
    Assert.fail();
  }
  catch (DelegationTokenManagerException ex) {
    Assert.assertTrue(ex.toString().contains("DT01"));
  }
}
项目:hadoop-plus    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testRenewToken(AuthenticationHandler handler)
  throws Exception {
  DelegationTokenoperation op =
    DelegationTokenoperation.RENEWDELEGATIONTOKEN;
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
    thenReturn(op.toString());
  Mockito.when(request.getmethod()).
    thenReturn(op.getHttpMethod());

  Assert.assertFalse(handler.managementOperation(null,Mockito.contains("equires SPNEGO authentication established"));

  Mockito.reset(response);
  AuthenticationToken token = Mockito.mock(AuthenticationToken.class);
  Mockito.when(token.getUserName()).thenReturn("user");
  Assert.assertFalse(handler.managementOperation(token,Mockito.contains("requires the parameter [token]"));

  Mockito.reset(response);
  StringWriter writer = new StringWriter();
  PrintWriter pwriter = new PrintWriter(writer);
  Mockito.when(response.getWriter()).thenReturn(pwriter);
  Token<DelegationTokenIdentifier> dToken =
    HttpFSServerWebApp.get().get(DelegationTokenManager.class).createtoken(
      UserGroupinformation.getCurrentUser(),"user");
  Mockito.when(request.getParameter(HttpFSKerberosAuthenticator.TOKEN_ParaM)).
    thenReturn(dToken.encodetoUrlString());
  Assert.assertFalse(handler.managementOperation(token,response));
  Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);
  pwriter.close();
  Assert.assertTrue(writer.toString().contains("long"));
  HttpFSServerWebApp.get().get(DelegationTokenManager.class).verifyToken(dToken);
}
项目:incubator-atlas    文件:AtlasAuthenticationFilter.java   
@Override
protected AuthenticationToken getToken(HttpServletRequest request)
        throws IOException,AuthenticationException {
    AuthenticationToken token = null;
    String tokenStr = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) {
                tokenStr = cookie.getValue();
                try {
                    tokenStr = this.signer.verifyAndExtract(tokenStr);
                } catch (SignerException ex) {
                    throw new AuthenticationException(ex);
                }
            }
        }
    }

    if (tokenStr != null) {
        token = AuthenticationToken.parse(tokenStr);
        if (token != null) {
            AuthenticationHandler authHandler = getAuthenticationHandler();
            if (!token.getType().equals(authHandler.getType())) {
                throw new AuthenticationException("Invalid AuthenticationToken type");
            }
            if (token.isExpired()) {
                throw new AuthenticationException("AuthenticationToken expired");
            }
        }
    }
    return token;
}
项目:hops    文件:TestHttpFSKerberosAuthenticationHandler.java   
@Test
@TestDir
public void testManagementOperations() throws Exception {
  String dir = TestDirHelper.getTestDir().getAbsolutePath();

  Configuration httpfsConf = new Configuration(false);
  HttpFSServerWebApp server =
      new HttpFSServerWebApp(dir,14000));
  AuthenticationHandler handler =
      new HttpFSKerberosAuthenticationHandlerForTesting();
  try {
    server.init();
    handler.init(null);

    testNonManagementOperation(handler);
    testManagementOperationErrors(handler);
    testGetToken(handler,"foo");
    testCancelToken(handler);
    testRenewToken(handler);

  } finally {
    if (handler != null) {
      handler.destroy();
    }
    server.destroy();
  }
}
项目:hops    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testNonManagementOperation(AuthenticationHandler handler)
    throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
      thenReturn(null);
  Assert.assertTrue(handler.managementOperation(null,null));
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
      thenReturn(HttpFSFileSystem.Operation.CREATE.toString());
  Assert.assertTrue(handler.managementOperation(null,null));
}
项目:hops    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testCancelToken(AuthenticationHandler handler) throws Exception {
  DelegationTokenoperation op =
      DelegationTokenoperation.CANCELDELEGATIONTOKEN;
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
      thenReturn(op.toString());
  Mockito.when(request.getmethod()).
      thenReturn(op.getHttpMethod());

  Assert.assertFalse(handler.managementOperation(null,Mockito.contains("requires the parameter [token]"));

  Mockito.reset(response);
  Token<DelegationTokenIdentifier> token =
      HttpFSServerWebApp.get().get(DelegationTokenManager.class)
          .createtoken(UserGroupinformation.getCurrentUser(),"foo");
  Mockito.when(request.getParameter(HttpFSKerberosAuthenticator.TOKEN_ParaM)).
      thenReturn(token.encodetoUrlString());
  Assert.assertFalse(handler.managementOperation(null,response));
  Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);
  try {
    HttpFSServerWebApp.get().get(DelegationTokenManager.class)
        .verifyToken(token);
    Assert.fail();
  } catch (DelegationTokenManagerException ex) {
    Assert.assertTrue(ex.toString().contains("DT01"));
  }
}
项目:hops    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testRenewToken(AuthenticationHandler handler) throws Exception {
  DelegationTokenoperation op = DelegationTokenoperation.RENEWDELEGATIONTOKEN;
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
      thenReturn(op.toString());
  Mockito.when(request.getmethod()).
      thenReturn(op.getHttpMethod());

  Assert.assertFalse(handler.managementOperation(null,Mockito.contains("requires the parameter [token]"));

  Mockito.reset(response);
  StringWriter writer = new StringWriter();
  PrintWriter pwriter = new PrintWriter(writer);
  Mockito.when(response.getWriter()).thenReturn(pwriter);
  Token<DelegationTokenIdentifier> dToken =
      HttpFSServerWebApp.get().get(DelegationTokenManager.class)
          .createtoken(UserGroupinformation.getCurrentUser(),"user");
  Mockito.when(request.getParameter(HttpFSKerberosAuthenticator.TOKEN_ParaM)).
      thenReturn(dToken.encodetoUrlString());
  Assert.assertFalse(handler.managementOperation(token,response));
  Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);
  pwriter.close();
  Assert.assertTrue(writer.toString().contains("long"));
  HttpFSServerWebApp.get().get(DelegationTokenManager.class)
      .verifyToken(dToken);
}
项目:hadoop-TCP    文件:TestHttpFSKerberosAuthenticationHandler.java   
@Test
@TestDir
public void testManagementOperations() throws Exception {
  String dir = TestDirHelper.getTestDir().getAbsolutePath();

  Configuration httpfsConf = new Configuration(false);
  HttpFSServerWebApp server =
    new HttpFSServerWebApp(dir,"foo");
    testCancelToken(handler);
    testRenewToken(handler);

  } finally {
    if (handler != null) {
      handler.destroy();
    }
  server.destroy();
  }
}
项目:hadoop-TCP    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testNonManagementOperation(AuthenticationHandler handler)
  throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
    thenReturn(null);
  Assert.assertTrue(handler.managementOperation(null,null));
}
项目:hadoop-TCP    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testCancelToken(AuthenticationHandler handler)
  throws Exception {
  DelegationTokenoperation op =
    DelegationTokenoperation.CANCELDELEGATIONTOKEN;
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
    thenReturn(op.toString());
  Mockito.when(request.getmethod()).
    thenReturn(op.getHttpMethod());

  Assert.assertFalse(handler.managementOperation(null,response));
  Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);
  try {
    HttpFSServerWebApp.get().get(DelegationTokenManager.class).verifyToken(token);
    Assert.fail();
  }
  catch (DelegationTokenManagerException ex) {
    Assert.assertTrue(ex.toString().contains("DT01"));
  }
}
项目:hadoop-TCP    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testRenewToken(AuthenticationHandler handler)
  throws Exception {
  DelegationTokenoperation op =
    DelegationTokenoperation.RENEWDELEGATIONTOKEN;
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
    thenReturn(op.toString());
  Mockito.when(request.getmethod()).
    thenReturn(op.getHttpMethod());

  Assert.assertFalse(handler.managementOperation(null,response));
  Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);
  pwriter.close();
  Assert.assertTrue(writer.toString().contains("long"));
  HttpFSServerWebApp.get().get(DelegationTokenManager.class).verifyToken(dToken);
}
项目:hardfs    文件:TestHttpFSKerberosAuthenticationHandler.java   
@Test
@TestDir
public void testManagementOperations() throws Exception {
  String dir = TestDirHelper.getTestDir().getAbsolutePath();

  Configuration httpfsConf = new Configuration(false);
  HttpFSServerWebApp server =
    new HttpFSServerWebApp(dir,"foo");
    testCancelToken(handler);
    testRenewToken(handler);

  } finally {
    if (handler != null) {
      handler.destroy();
    }
  server.destroy();
  }
}
项目:hardfs    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testNonManagementOperation(AuthenticationHandler handler)
  throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
    thenReturn(null);
  Assert.assertTrue(handler.managementOperation(null,null));
}
项目:hardfs    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testCancelToken(AuthenticationHandler handler)
  throws Exception {
  DelegationTokenoperation op =
    DelegationTokenoperation.CANCELDELEGATIONTOKEN;
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
    thenReturn(op.toString());
  Mockito.when(request.getmethod()).
    thenReturn(op.getHttpMethod());

  Assert.assertFalse(handler.managementOperation(null,response));
  Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);
  try {
    HttpFSServerWebApp.get().get(DelegationTokenManager.class).verifyToken(token);
    Assert.fail();
  }
  catch (DelegationTokenManagerException ex) {
    Assert.assertTrue(ex.toString().contains("DT01"));
  }
}
项目:hardfs    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testRenewToken(AuthenticationHandler handler)
  throws Exception {
  DelegationTokenoperation op =
    DelegationTokenoperation.RENEWDELEGATIONTOKEN;
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
    thenReturn(op.toString());
  Mockito.when(request.getmethod()).
    thenReturn(op.getHttpMethod());

  Assert.assertFalse(handler.managementOperation(null,response));
  Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);
  pwriter.close();
  Assert.assertTrue(writer.toString().contains("long"));
  HttpFSServerWebApp.get().get(DelegationTokenManager.class).verifyToken(dToken);
}
项目:hadoop-on-lustre2    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testManagementOperations(Text expectedTokenKind) throws Exception {
  String dir = TestDirHelper.getTestDir().getAbsolutePath();

  Configuration httpfsConf = new Configuration(false);
  HttpFSServerWebApp server =
    new HttpFSServerWebApp(dir,null,expectedTokenKind);
    testGetToken(handler,"foo",expectedTokenKind);
    testCancelToken(handler);
    testRenewToken(handler);

  } finally {
    if (handler != null) {
      handler.destroy();
    }
  server.destroy();
  }
}
项目:hadoop-on-lustre2    文件:TestHttpFSKerberosAuthenticationHandler.java   
private void testNonManagementOperation(AuthenticationHandler handler)
  throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  Mockito.when(request.getParameter(HttpFSFileSystem.OP_ParaM)).
    thenReturn(null);
  Assert.assertTrue(handler.managementOperation(null,null));
}

org.springframework.security.authentication.AuthenticationDetailsSource的实例源码

org.springframework.security.authentication.AuthenticationDetailsSource的实例源码

项目:syndesis    文件:SecurityConfiguration.java   
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
private RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter() throws Exception {
    RequestHeaderAuthenticationFilter f = new RequestHeaderAuthenticationFilter();
    f.setPrincipalRequestHeader("X-Forwarded-User");
    f.setCredentialsRequestHeader("X-Forwarded-Access-Token");
    f.setAuthenticationManager(authenticationManager());
    f.setAuthenticationDetailsSource(
        (AuthenticationDetailsSource<HttpServletRequest,PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails>)
            (request) ->new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
                request,AuthorityUtils.createAuthorityList("ROLE_AUTHENTICATED")
            )
    );
    f.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler());
    f.setExceptionIfheaderMissing(false);
    return f;
}
项目:syndesis-rest    文件:SecurityConfiguration.java   
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
private RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter() throws Exception {
    RequestHeaderAuthenticationFilter f = new RequestHeaderAuthenticationFilter();
    f.setPrincipalRequestHeader("X-Forwarded-User");
    f.setCredentialsRequestHeader("X-Forwarded-Access-Token");
    f.setAuthenticationManager(authenticationManager());
    f.setAuthenticationDetailsSource(
        (AuthenticationDetailsSource<HttpServletRequest,AuthorityUtils.createAuthorityList("ROLE_AUTHENTICATED")
            )
    );
    f.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler());
    f.setExceptionIfheaderMissing(false);
    return f;
}
项目:cf-sample-service    文件:DashboardAuthenticationProcessingFilterTest.java   
@Test
public void attemptAuthenticationWithDetailSource() throws IOException,servletexception {
    final OAuth2Authentication oAuth2Authentication = createAuthentication();
    final Object details = "details";
    final Authentication resultAuthentication = createResultAuthentication(oAuth2Authentication);

    final HttpServletRequest request = createRequest();
    final AuthenticationDetailsSource<HttpServletRequest,?> detailsSource = createDetailsSource(request,details);

    final DashboardAuthenticationProcessingFilter filter =
          createFilter(oAuth2Authentication,resultAuthentication,detailsSource);

    final Authentication actualResultAuthentication = filter.attemptAuthentication(request,createResponse());

    assertSame(resultAuthentication,actualResultAuthentication);
    assertEquals(details,oAuth2Authentication.getDetails());
}
项目:communote-server    文件:AuthenticationHelper.java   
/**
 * Set the public user as authenticated user to the current SecurityContext. If the
 * SecurityContext is shared between all threads of the current session.
 *
 * @param request
 *            the servlet request
 */
public static void setPublicUserToSecurityContext(ServletRequest request) {
    org.springframework.security.core.userdetails.User user = new PublicUserDetails();
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
            user,user.getpassword(),user.getAuthorities());
    AuthenticationDetailsSource<Object,Object> authenticationDetailsSource = new AuthenticationDetailsSourceImpl();
    authentication.setDetails(authenticationDetailsSource.buildDetails(request));
    SecurityContextHolder.getContext().setAuthentication(authentication);
}
项目:artifactory    文件:AccessFilter.java   
@SuppressWarnings({"ThrowableInstanceNeverThrown"})
private void useAnonymousIfPossible(HttpServletRequest request,HttpServletResponse response,FilterChain chain,SecurityContext securityContext) throws IOException,servletexception {
    boolean anonAccessEnabled = context.getAuthorizationService().isAnonAccessEnabled();
    if (anonAccessEnabled || authInterceptors.accept(request)) {
        log.debug("Using anonymous");
        Authentication authentication = getNonUiCachedAuthentication(request);
        if (authentication == null) {
            log.debug("Creating the Anonymous token");
            final UsernamePasswordAuthenticationToken authRequest =
                    new UsernamePasswordAuthenticationToken(UserInfo.ANONYMOUS,"");
            AuthenticationDetailsSource ads = new HttpAuthenticationDetailsSource();
            //noinspection unchecked
            authRequest.setDetails(ads.buildDetails(request));
            // explicitly ask for the default spring authentication manager by name (we have another one which
            // is only used by the basic authentication filter)
            AuthenticationManager authenticationManager =
                    context.beanForType("authenticationManager",AuthenticationManager.class);
            authentication = authenticationManager.authenticate(authRequest);
            if (authentication != null && authentication.isAuthenticated() && !RequestUtils.isUiRequest(request)) {
                AuthCacheKey authCacheKey = new AuthCacheKey(authFilter.getCacheKey(request),request.getRemoteAddr());
                nonUiAuthCache.put(authCacheKey,authentication);
                log.debug("Added anonymous authentication {} to cache",authentication);
            }
        } else {
            log.debug("Using cached anonymous authentication");
        }
        useAuthentication(request,response,chain,authentication,securityContext);
    } else {
        if (authFilter.acceptEntry(request)) {
            log.debug("Sending request requiring authentication");
            authFilter.commence(request,new InsufficientAuthenticationException("Authentication is required"));
        } else {
            log.debug("No filter or entry just chain");
            chain.doFilter(request,response);
        }
    }
}
项目:jeffaschenk-commons    文件:AuthenticationFilter.java   
@Override
public void setAuthenticationDetailsSource
        (AuthenticationDetailsSource
                 authenticationDetailsSource) {
    log.debug("Invoking setAuthenticationDetailsSource");
    super.setAuthenticationDetailsSource(authenticationDetailsSource);
}
项目:cf-sample-service    文件:DashboardAuthenticationProcessingFilterTest.java   
private DashboardAuthenticationProcessingFilter createFilter(OAuth2Authentication oAuth2Authentication,Authentication resultAuthentication,AuthenticationDetailsSource<HttpServletRequest,?> source) {
    final String token = "TOKEN";
    final DashboardAuthenticationProcessingFilter filter = new DashboardAuthenticationProcessingFilter();

    filter.setAuthenticationManager(createAuthenticationManagerForUserAuth(oAuth2Authentication,resultAuthentication));
    filter.setRestTemplate(createRestTemplate(token));
    filter.setTokenServices(createResourcetokenServices(oAuth2Authentication,token));
    filter.setDetailsSource(source);

    return filter;
}
项目:cf-sample-service    文件:DashboardAuthenticationProcessingFilterTest.java   
@SuppressWarnings("unchecked")
private AuthenticationDetailsSource<HttpServletRequest,?> createDetailsSource(HttpServletRequest request,Object details) {
    final AuthenticationDetailsSource<HttpServletRequest,?> source = mock(AuthenticationDetailsSource.class);

    when(source.buildDetails(request))
          .thenReturn(details);

    return source;
}
项目:haven-platform    文件:TokenAuthFilterConfigurer.java   
public AuthenticationDetailsSource<HttpServletRequest,?> getAuthenticationDetailsSource() {
    return authenticationDetailsSource;
}
项目:haven-platform    文件:TokenAuthFilterConfigurer.java   
public void setAuthenticationDetailsSource(AuthenticationDetailsSource<HttpServletRequest,?> authenticationDetailsSource) {
    this.authenticationDetailsSource = authenticationDetailsSource;
}
项目:communote-server    文件:RequestParameterauthenticationProcessingFilter.java   
/**
 * @param authenticationDetailsSource
 *            the {@link AuthenticationDetailsSource} to use,cannot be null
 */
public void setAuthenticationDetailsSource(
        AuthenticationDetailsSource<Object,Object> authenticationDetailsSource) {
    Assert.notNull(authenticationDetailsSource,"AuthenticationDetailsSource required");
    this.authenticationDetailsSource = authenticationDetailsSource;
}
项目:putput    文件:AccesstokenAuthenticationFilter.java   
private AuthenticationDetailsSource<HttpServletRequest,?> detailsSource() {
    return (request) -> {
        Collection<? extends GrantedAuthority> authorities = Collections.singleton(new SimpleGrantedAuthority("ROLE_USER"));
        return new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(request,authorities);
    };
}
项目:cloudstreetmarket.com    文件:CustomOAuth2RequestFilter.java   
public void setAuthenticationDetailsSource(
        AuthenticationDetailsSource<HttpServletRequest,?> authenticationDetailsSource) {
    Assert.notNull(authenticationDetailsSource,"AuthenticationDetailsSource required");
    this.authenticationDetailsSource = authenticationDetailsSource;
}
项目:aggregate    文件:BasicAuthenticationFilter.java   
public void  setAuthenticationDetailsSource(AuthenticationDetailsSource<javax.servlet.http.HttpServletRequest,?> authenticationDetailsSource) {
  impl.setAuthenticationDetailsSource(authenticationDetailsSource);
}
项目:summerb    文件:RestLoginFilter.java   
public AuthenticationDetailsSource<HttpServletRequest,?> getAuthenticationDetailsSource() {
    return authenticationDetailsSource;
}
项目:summerb    文件:RestLoginFilter.java   
public void setAuthenticationDetailsSource(
        AuthenticationDetailsSource<HttpServletRequest,?> authenticationDetailsSource) {
    this.authenticationDetailsSource = authenticationDetailsSource;
}
项目:eHMP    文件:VistaBasicAuthenticationFilter.java   
public void setAuthenticationDetailsSource(AuthenticationDetailsSource authenticationDetailsSource) {
    Assert.notNull(authenticationDetailsSource,"AuthenticationDetailsSource required");
    this.authenticationDetailsSource = authenticationDetailsSource;
}
项目:appverse-server    文件:CustomUserNamePasswordAuthenticationFilter.java   
public void setAuthenticationDetailsSource(
        AuthenticationDetailsSource<HttpServletRequest,"AuthenticationDetailsSource required");
    this.authenticationDetailsSource = authenticationDetailsSource;
}
项目:jeffaschenk-commons    文件:AuthenticationFilter.java   
@Override
public AuthenticationDetailsSource getAuthenticationDetailsSource
        () {
    log.debug("Invoking getAuthenticationDetailsSource");
    return super.getAuthenticationDetailsSource();
}
项目:cf-sample-service    文件:DashboardAuthenticationProcessingFilter.java   
/**
 * Sets the optional source providing {@link Authentication#getDetails() authentication details}.
 */
public void setDetailsSource(AuthenticationDetailsSource<HttpServletRequest,?> detailsSource) {
    this.detailsSource = detailsSource;
}
项目:cf-sample-service    文件:DashboardSecurityConfiguration.java   
@Bean(name = "dashboardAuthenticationDetailsSource")
@Autowired
public AuthenticationDetailsSource<HttpServletRequest,?> dashboardAuthenticationDetailsSource() {
    return new DashboardAuthenticationDetailsSource(dashboardRestOperations(),suidFile,oauthInfoUrl,apiUrl);
}
项目:oauth-client-master    文件:OAuth2AuthenticationProcessingFilter.java   
/**
 * @param authenticationDetailsSource
 *            The AuthenticationDetailsSource to use
 */
public void setAuthenticationDetailsSource(AuthenticationDetailsSource<HttpServletRequest,"AuthenticationDetailsSource required");
    this.authenticationDetailsSource = authenticationDetailsSource;
}
项目:molgenis    文件:MolgenisAnonymousAuthenticationFilter.java   
public void setAuthenticationDetailsSource(
        AuthenticationDetailsSource<HttpServletRequest,?> authenticationDetailsSource)
{
    Assert.notNull(authenticationDetailsSource,"AuthenticationDetailsSource required");
    this.authenticationDetailsSource = authenticationDetailsSource;
}
项目:termitaria    文件:TokenBasedAuthenticationFilter.java   
public void setAuthenticationDetailsSource(
        AuthenticationDetailsSource authenticationDetailsSource) {
    Assert.notNull(authenticationDetailsSource,"AuthenticationDetailsSource required");
    this.authenticationDetailsSource = authenticationDetailsSource;
}
项目:communote-server    文件:XMPPAuthenticationProcessingFilter.java   
/**
 * Sets the authentication details source.
 *
 * @param authenticationDetailsSource
 *            the auth details source.
 */
public final void setAuthenticationDetailsSource(
        AuthenticationDetailsSource<Object,"AuthenticationDetailsSource required");
    this.authenticationDetailsSource = authenticationDetailsSource;
}
项目:oauth-client-master    文件:TokenEndpointAuthenticationFilter.java   
/**
 * A source of authentication details for requests that result in authentication.
 * 
 * @param authenticationDetailsSource the authenticationDetailsSource to set
 */
public void setAuthenticationDetailsSource(
        AuthenticationDetailsSource<HttpServletRequest,?> authenticationDetailsSource) {
    this.authenticationDetailsSource = authenticationDetailsSource;
}

今天关于使用AuthenticationFailureHandler在Spring Security中自定义身份验证失败响应spring security oauth2自定义认证的讲解已经结束,谢谢您的阅读,如果想了解更多关于@Autowire在Spring Security自定义身份验证提供程序中不起作用、java – 自定义authenticationFilter Spring Security 3.2、org.apache.hadoop.security.authentication.server.AuthenticationHandler的实例源码、org.springframework.security.authentication.AuthenticationDetailsSource的实例源码的相关知识,请在本站搜索。

本文标签: