Тест Spring Security Filter, аутентификация не работает в POSTMAN - PullRequest
1 голос
/ 21 февраля 2020

Я пытаюсь проверить, работает ли tryAuthentication, но в почтальоне, но я получаю 401 несанкционированных.

Моя защита Настройка:

 @Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    //http.formLogin();
    http.authorizeRequests().antMatchers("/login","/login/**","/register/**").permitAll();
    http.authorizeRequests().antMatchers(HttpMethod.POST,"/tasks/**").hasAuthority("ADMIN");
    http.authorizeRequests().anyRequest().authenticated();
    http.addFilter(new JWTAuthenticationFilter(authenticationManager()));
    http.addFilterBefore(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);


}

Моя попыткаAuthentication:

@Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {

        AppUser appUser = null;
        try {

            appUser = new ObjectMapper().readValue(request.getInputStream(), AppUser.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("****************************");
        System.out.println(appUser.getUsername());
        return authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(appUser.getUsername(), appUser.getPassword()));
    }

Мой тест почтальона: enter image description here

Мой JWTAuthenticationFilter:

package security;

import java.io.IOException;
import java.util.Date;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.example.springJWT.entities.AppUser;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;



public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter{


    private AuthenticationManager authenticationManager;    


    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        super();
        //      super.setFilterProcessesUrl("/login");

        this.authenticationManager = authenticationManager;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {

        AppUser appUser = null;
        try {

            appUser = new ObjectMapper().readValue(request.getInputStream(), AppUser.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("****************************");
        System.out.println(appUser.getUsername());
        return authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(appUser.getUsername(), appUser.getPassword()));
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
            Authentication authResult) throws IOException, ServletException {
        User springUser=(User) authResult.getPrincipal();
        String jwt=Jwts.builder()
                .setSubject(springUser.getUsername())
                .setExpiration(new Date(System.currentTimeMillis()+SecurityConstants.EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS256, SecurityConstants.SECRET)
                .claim("roles", springUser.getAuthorities())
                .compact();
        response.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX+jwt);
        super.successfulAuthentication(request, response, chain, authResult);
    }
}

1 Ответ

0 голосов
/ 22 февраля 2020

в вашем классе JWTAuthenticationFilter в методе attemptAuthentication, который вы предоставляете UsernamePasswordAuthenticationToken для менеджера аутентификации

, который имеет в качестве основного экземпляра String и в методе successfulAuthentication, который вы пытаетесь чтобы привести это к Пользователю

User springUser=(User) authResult.getPrincipal();

, и если я попробую, это пойдет не так, но это зависит от AuthenticationProvider, который вы фактически используете

...