使用自定义AuthenticationProvider成功登录后,Principal为null

时间:2017-07-31 17:56:31

标签: java spring spring-security

我使用休息服务制作了自定义AuthenticationProvider:

@Component
public class RestAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();
        //
        RestTemplate restTemplate = new RestTemplate();
        try {
            ResponseEntity<Session> res = restTemplate.exchange("http://localhost:8081/login", HttpMethod.POST, new HttpEntity<>(createHeaders(name, password)), Session.class);
            Collection<? extends GrantedAuthority> authorities = Collections.singleton(new SimpleGrantedAuthority("ROLE_USER"));
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(name, null, authorities);
            //authenticationToken.setDetails(res.getBody());
            //
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            //
            return authenticationToken;
            //return new UsernamePasswordAuthenticationToken(name, password);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(
                UsernamePasswordAuthenticationToken.class);
    }

    HttpHeaders createHeaders(final String username, final String password) {
        return new HttpHeaders() {{
            set("user", username);
            set("realm", "realm");
            set("password", password);
        }};
    }

}

这很好用。调用该服务,并返回带有该信息的authenticationToken。然后是映射&#34; /&#34;被称为:

@Controller
public class MainController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Principal principal, ModelMap model) {
        return principal != null ? "home/loggedIn" : "home/notLoggedIn";
    }
}

主体为空。我已经读过我需要设置securityContext但是添加:

SecurityContextHolder.getContext().setAuthentication(authenticationToken);

没有工作。

Eddit

要添加更多内容,这是我的安全配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private RestAuthenticationProvider authProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .authenticationProvider(authProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .authorizeRequests()
                .antMatchers("/", "/favicon.ico", "/resources/**", "/signup", "/signin", "/about").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/signin")
                .permitAll()
                .failureUrl("/signin?error=1")
                .loginProcessingUrl("/authenticate")
                .and()
                .httpBasic()
                .and()
                .logout()
                .logoutUrl("/logout")
                .permitAll()
                .logoutSuccessUrl("/signin?logout")
                .and()
                .rememberMe()
                .tokenValiditySeconds(1209600)
                .and()
                .csrf().disable()
        ;
    }

}

1 个答案:

答案 0 :(得分:0)

问题是我在嵌入式Jetty上运行它:

        <!-- embedded Jetty server, for testing -->
        <plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>9.2.11.v20150529</version>
            <configuration>
                <scanIntervalSeconds>10</scanIntervalSeconds>
                <webApp>
                    <contextPath>/mssgui</contextPath>
                </webApp>
            </configuration>
        </plugin>

为tomcat更改了它,现在它正在工作:

        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.1</version>
            <configuration>
                <path>/</path>
            </configuration>
        </plugin>