春季-所有请求都将转到相同的映射

时间:2018-11-25 08:56:15

标签: java spring rest

我不知道这是怎么发生的,因为我没有做大的更改,但是现在我对spring服务器应用程序所做的所有请求都由同一服务响应。

我的build.gradle(完全没有安全性)

我的主(没什么大不了的)

@SpringBootApplication
public class PolifoniaApplication {

    public static void main(String[] args) {
    SpringApplication.run(PolifoniaApplication.class, args);
    }
}

我的控制器(即使来自另一个类的每个单个请求都进入“ / login”,我什至对Mapping行进行注释,并且它会继续登录)。即使是不存在的URI,它也会进入“ /登录”服务

@CrossOrigin
@RestController
public class UsuarioController {

Logger logger = LoggerFactory.getLogger(UsuarioController.class);

private static final String ESTUDIANTE_GROUP = "ou=people,dc=springframework,dc=org";
private static final String PROFESOR_GROUP = "ou=otherpeople,dc=springframework,dc=org";
private static final String ADMINISTRATIVO_GROUP = "ou=space cadets,dc=springframework,dc=org";

@Autowired
private LdapTemplate ldapTemplate;

@Autowired
private UsuarioRepository usuarioRepository;

@Autowired
private SesionRepository sesionRepository;

@GetMapping("/all")
public List<String> getAllPersonNames() {
    return ldapTemplate.search(query().where("objectclass").is("person"), new AttributesMapper<String>() {
        public String mapFromAttributes(Attributes attrs) throws NamingException {
            return attrs.get("sn").get().toString();
        }
    });
}

/**
 * Servicio de confirmación de login con LDAP o por token
 * @param authData - información de seguridad
 * @return String con token si se generó
 */
@PostMapping("/login")
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> autenticar(@RequestBody AuthData authData) {
    ResponseEntity<String> response;

    boolean correcto = ldapTemplate.authenticate("", String.format("(uid=%s)", authData.getUsername()), authData.getPassword());

    if (correcto) {
        Usuario usuario = buscarUsuarioLdap(authData);
        Sesion sesion = new Sesion(authData, usuario.getId());
        response = ResponseEntity.status(HttpStatus.OK).body(Utilities.stringToJson("token", sesion.getToken()));   
        sesionRepository.save(sesion);
    } else {
        throw new AuthPolifoniaException();         
    }

    return response;
}

/** 
 * Método que registra un usuario que ingresa por primera vez a la aplicación
 * @param authData - Datos del usuario
 */
private Usuario buscarUsuarioLdap(AuthData authData) {
    Usuario usuario = usuarioRepository.findByUsername(authData.getUsername()); 

    if (usuario == null) {
        TipoUsuario tipoUsuario = TipoUsuario.ESTUDIANTE;           

        LdapQuery estudianteQuery = LdapQueryBuilder.query().base(ESTUDIANTE_GROUP).searchScope(SearchScope.SUBTREE)
                .filter(new EqualsFilter("uid", authData.getUsername()));

        List<String> result = ldapTemplate.search(estudianteQuery, new AttributesMapper<String>() {
            public String mapFromAttributes(Attributes attrs) throws NamingException {
                return attrs.get("cn").get().toString();
            }
        });

        if (result.isEmpty()) {
            tipoUsuario = TipoUsuario.PROFESOR;
            LdapQuery profesorQuery = LdapQueryBuilder.query().base(PROFESOR_GROUP).searchScope(SearchScope.SUBTREE)
                    .filter(new EqualsFilter("uid", authData.getUsername()));

            result = ldapTemplate.search(profesorQuery, new AttributesMapper<String>() {
                public String mapFromAttributes(Attributes attrs) throws NamingException {
                    return attrs.get("cn").get().toString();
                }
            });
        }

        if (result.isEmpty()) {
            tipoUsuario = TipoUsuario.ADMINISTRATIVO;
            LdapQuery administrativoQuery = LdapQueryBuilder.query().base(ADMINISTRATIVO_GROUP)
                    .searchScope(SearchScope.SUBTREE).filter(new EqualsFilter("uid", authData.getUsername()));
            result = ldapTemplate.search(administrativoQuery, new AttributesMapper<String>() {
                public String mapFromAttributes(Attributes attrs) throws NamingException {
                    return attrs.get("cn").get().toString();
                }
            }); 
        }


        if (result.isEmpty()) {
            tipoUsuario = null;
        }

        usuario = new Usuario(result.get(0), authData.getUsername(), tipoUsuario);
        usuarioRepository.save(usuario);
    }
    return usuario;
}

/**
 * Servicio que destruye el token de sesión
 * @param authData - Datos del usuario (token)
 */
@PostMapping("/logout")
public void logout(@RequestHeader(HttpHeaders.WWW_AUTHENTICATE) String token) {
    sesionRepository.deleteById(token);
 }

我有一个有效的建议。看来,如果我运行测试可以正常工作。我找不到任何逻辑,这是疯狂的。 我试图评论该方法,但是服务器根本没有任何答案。

这是自从我发送请求以来的日志(在本例中为“ localhost:8080 / comunidades”,但是所有服务(甚至是“ / logout”)都发生了这种情况)

2018-11-25 10:50:12.981 DEBUG 11840 --- [nio-8080-exec-3] o.a.tomcat.util.net.SocketWrapperBase    : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@d601e02:org.apache.tomcat.util.net.NioChannel@75d2ecd0:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8080 remote=/0:0:0:0:0:0:0:1:7687]], Read from buffer: [0]
2018-11-25 10:50:12.982 DEBUG 11840 --- [nio-8080-exec-3] org.apache.tomcat.util.net.NioEndpoint   : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@d601e02:org.apache.tomcat.util.net.NioChannel@75d2ecd0:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8080 remote=/0:0:0:0:0:0:0:1:7687]], Read direct from socket: [301]
2018-11-25 10:50:12.983 DEBUG 11840 --- [nio-8080-exec-3] o.a.coyote.http11.Http11InputBuffer      : Received [GET /comunidades HTTP/1.1
Content-Type: application/json
cache-control: no-cache
Postman-Token: e30db580-fcdd-4c95-8195-f16b9186420a
User-Agent: PostmanRuntime/7.4.0
Accept: */*
Host: localhost:8080
accept-encoding: gzip, deflate
content-length: 17
Connection: keep-alive

{
    "pageNum": 1
}]
2018-11-25 10:50:12.998 DEBUG 11840 --- [nio-8080-exec-3] o.a.c.authenticator.AuthenticatorBase    : Security checking request GET /comunidades
2018-11-25 10:50:12.998 DEBUG 11840 --- [nio-8080-exec-3] org.apache.catalina.realm.RealmBase      :   No applicable constraints defined
2018-11-25 10:50:12.998 DEBUG 11840 --- [nio-8080-exec-3] o.a.c.authenticator.AuthenticatorBase    :  Not subject to any constraint
2018-11-25 10:50:12.999 DEBUG 11840 --- [nio-8080-exec-3] org.apache.tomcat.util.http.Parameters   : Set encoding to UTF-8
2018-11-25 10:50:12.999 DEBUG 11840 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : GET "/comunidades", parameters={}
2018-11-25 10:50:12.999 DEBUG 11840 --- [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public org.springframework.http.ResponseEntity<java.lang.String> com.poligran.polifonia.controllers.UsuarioController.autenticar(com.poligran.polifonia.utilities.AuthData)
2018-11-25 10:50:13.000 DEBUG 11840 --- [nio-8080-exec-3] o.j.s.OpenEntityManagerInViewInterceptor : Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2018-11-25 10:50:13.001 DEBUG 11840 --- [nio-8080-exec-3] m.m.a.RequestResponseBodyMethodProcessor : Read "application/json;charset=UTF-8" to [AUTHDATA - User: null, Password: null]
2018-11-25 10:50:13.003 DEBUG 11840 --- [nio-8080-exec-3] o.s.l.c.support.AbstractContextSource    : Got Ldap context on server 'ldap://localhost:12345'
2018-11-25 10:50:13.004  INFO 11840 --- [nio-8080-exec-3] o.s.ldap.core.LdapTemplate               : No results found for search, base: ''; filter: '(uid=null)'.
2018-11-25 10:50:13.004 DEBUG 11840 --- [nio-8080-exec-3] .m.m.a.ExceptionHandlerExceptionResolver : Using @ExceptionHandler com.poligran.polifonia.utilities.ErrorMessage com.poligran.polifonia.advices.AuthAdvice.dataNotFoundHandler(com.poligran.polifonia.exceptions.AuthPolifoniaException)
2018-11-25 10:50:13.005 DEBUG 11840 --- [nio-8080-exec-3] m.m.a.RequestResponseBodyMethodProcessor : Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json]
2018-11-25 10:50:13.005 DEBUG 11840 --- [nio-8080-exec-3] m.m.a.RequestResponseBodyMethodProcessor : Writing [com.poligran.polifonia.utilities.ErrorMessage@6fd9c4ca]
2018-11-25 10:50:13.008  WARN 11840 --- [nio-8080-exec-3] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [com.poligran.polifonia.exceptions.AuthPolifoniaException: Error en la autenticación del usuario]
2018-11-25 10:50:13.008 DEBUG 11840 --- [nio-8080-exec-3] o.j.s.OpenEntityManagerInViewInterceptor : Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
2018-11-25 10:50:13.008 DEBUG 11840 --- [nio-8080-exec-3] o.s.orm.jpa.EntityManagerFactoryUtils    : Closing JPA EntityManager
2018-11-25 10:50:13.008 DEBUG 11840 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : Completed 401 UNAUTHORIZED
2018-11-25 10:50:13.009 DEBUG 11840 --- [nio-8080-exec-3] o.a.tomcat.util.net.SocketWrapperBase    : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@d601e02:org.apache.tomcat.util.net.NioChannel@75d2ecd0:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8080 remote=/0:0:0:0:0:0:0:1:7687]], Read from buffer: [0]
2018-11-25 10:50:13.009 DEBUG 11840 --- [nio-8080-exec-3] org.apache.tomcat.util.net.NioEndpoint   : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@d601e02:org.apache.tomcat.util.net.NioChannel@75d2ecd0:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8080 remote=/0:0:0:0:0:0:0:1:7687]], Read direct from socket: [0]
2018-11-25 10:50:13.009 DEBUG 11840 --- [nio-8080-exec-3] o.apache.coyote.http11.Http11Processor   : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@d601e02:org.apache.tomcat.util.net.NioChannel@75d2ecd0:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8080 remote=/0:0:0:0:0:0:0:1:7687]], Status in: [OPEN_READ], State out: [OPEN]
2018-11-25 10:50:22.583 DEBUG 11840 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Pool stats (total=10, active=0, idle=10, waiting=0)

非常感谢您的时间。

0 个答案:

没有答案