Spring Boot AntPathRequestMatchers, запрещающий управление доступом на основе ролей к конечной точкеJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Гость
 Spring Boot AntPathRequestMatchers, запрещающий управление доступом на основе ролей к конечной точке

Сообщение Гость »


Я новичок в Spring Boot и пытался реализовать ролевой доступ к конечной точке контроллера с использованием аутентификации токена носителя.

Я храню пользователей, пароли, роли в таблицах, используя MySQL. После перехода к конечной точке localhost:8080/login с именем пользователя и паролем я могу получить такие роли, как USER и ADMIN, но не могу получить доступ к конечным точкам /api/library/book. Я также могу создать пользователя, нажав конечную точку /api/user/createUser.

UserController.java

пакет com.api.controller; импортировать org.springframework.http.HttpStatus; импортировать org.springframework.http.ResponseEntity; импортировать org.springframework.web.bind.annotation.GetMapping; импортировать org.springframework.web.bind.annotation.PostMapping; импортировать org.springframework.web.bind.annotation.RequestBody; импортировать org.springframework.web.bind.annotation.RequestMapping; импортировать org.springframework.web.bind.annotation.RestController; импортировать com.api.model.request.UserCreateRequest; импортировать com.api.model.response.Response; импортировать com.api.service.UserService; импортировать ломбок.RequiredArgsConstructor; @RestController @RequestMapping("/api") @RequiredArgsConstructor публичный класс UserController { частный окончательный UserService userService; @PostMapping("/user/createUser") public ResponseEntity createUser(@RequestBody UserCreateRequest userCreateRequest){ userService.createNewUser(userCreateRequest); Ответ ответ = новый ответ(); response.setDescription("Успех"); response.setMessage("Пользователь успешно создан."); вернуть новый ResponseEntity(ответ, HttpStatus.OK); } @GetMapping("/библиотека/книга") общественный ResponseEntity book(){ Ответ ответ = новый ответ(); response.setDescription("Успех"); response.setMessage("Попадание в конечную точку /book"); вернуть новый ResponseEntity(ответ, HttpStatus.OK); } @GetMapping("/библиотека/автор") общественный ResponseEntity автор(){ Ответ ответ = новый ответ(); response.setDescription("Успех"); response.setMessage("Хит /конечная точка автора"); вернуть новый ResponseEntity(ответ, HttpStatus.OK); } } SecurityConfig.java

пакет com.api.config; импортировать org.springframework.context.annotation.Bean; импортировать org.springframework.context.annotation.Configuration; импортировать org.springframework.security.authentication.AuthenticationManager; импортировать org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; импортировать org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; импортировать org.springframework.security.config.annotation.web.builders.HttpSecurity; импортировать org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; импортировать org.springframework.security.config.http.SessionCreationPolicy; импортировать org.springframework.security.web.SecurityFilterChain; импортировать org.springframework.security.web.util.matcher.AntPathRequestMatcher; импортировать com.api.filter.JwtAuthenticationFilter; импортировать com.api.filter.JwtAuthorizationFilter; импортировать ломбок.RequiredArgsConstructor; @Конфигурация @EnableWebSecurity @EnableMethodSecurity @RequiredArgsConstructor общественный класс SecurityConfig { @Бин public SecurityFilterChain filterChain(HttpSecurity http) выдает исключение { System.out.println("Внутри SecurityConfig filterChain()"); http.csrf(csrf -> csrf.disable()) .authorizeHttpRequests(аутентификация -> аутентификация .requestMatchers(новый AntPathRequestMatcher(AuthenticationConfigConstants.SIGN_UP_URL)).permitAll() .requestMatchers(new AntPathRequestMatcher("/api/library/book")).hasAnyRole("ПОЛЬЗОВАТЕЛЬ","АДМИН") .requestMatchers(новый AntPathRequestMatcher("/api/library/author")).hasAnyRole("ADMIN") .requestMatchers(new AntPathRequestMatcher("/api/library/member")).hasAnyRole("ADMIN") .anyRequest().аутентифицированный() ) .addFilter(новый JwtAuthenticationFilter(authenticationManager(http.getSharedObject(AuthenticationConfiguration.class)))) .addFilter(новый JwtAuthorizationFilter(authenticationManager(http.getSharedObject(AuthenticationConfiguration.class)))) .sessionManagement(сесс -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); вернуть http.build(); } @Бин public AuthenticationManager AuthenticationManager (AuthenticationConfigurationauthenticationConfiguration) выдает исключение { System.out.println("Внутри SecurityConfig AuthenticationManager()"); вернуть аутентификациюConfiguration.getAuthenticationManager(); } } JwtAuthentication.java

пакет com.api.filter; импортировать java.io.IOException; импортировать java.util.ArrayList; импортировать java.util.Date; импортировать org.springframework.security.authentication.AuthenticationManager; импортировать org.springframework.security.authentication.BadCredentialsException; импортировать org.springframework.security.authentication.UsernamePasswordAuthenticationToken; импортировать org.springframework.security.core.Authentication; импортировать org.springframework.security.core.AuthenticationException; импортировать org.springframework.security.core.userdetails.User; импортировать org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; импортировать com.api.config.AuthenticationConfigConstants; импортировать com.api.model.ApiUser; импортировать com.auth0.jwt.JWT; импортировать com.auth0.jwt.algorithms.Algorithm; импортировать com.fasterxml.jackson.databind.ObjectMapper; импортировать jakarta.servlet.FilterChain; импортировать jakarta.servlet.ServletException; импортировать jakarta.servlet.http.HttpServletRequest; импортировать jakarta.servlet.http.HttpServletResponse; импортировать ломбок.RequiredArgsConstructor; @RequiredArgsConstructor общественный класс JwtAuthenticationFilter расширяет UsernamePasswordAuthenticationFilter { частный окончательный менеджер аутентификации AuthenticationManager; @Override общедоступная попытка аутентификацииAuthentication (запрос HttpServletRequest, ответ HttpServletResponse) выдает AuthenticationException { System.out.println("Внутри попытки JwtAuthenticationAuthentication()"); пытаться { ApiUser creds = новый ObjectMapper() .readValue(request.getInputStream(), ApiUser.class); if(creds.getUsername() == null || creds.getPassword() == null) { выдать новое исключение BadCredentialsException("Неверные учетные данные"); } вернуть аутентификациюManager.authenticate( новый UsernamePasswordAuthenticationToken( creds.getUsername(), creds.getPassword(), новый ArrayList() ) ); } catch(IOException e) { выдать новое RuntimeException(e); } } @Override protected void SuccessAuthentication (запрос HttpServletRequest, ответ HttpServletResponse, цепочка FilterChain, проверка подлинности) выдает IOException, ServletException { System.out.println("Внутри JwtAuthentication SuccessAuthentication()"); Строковый токен = JWT.create() .withSubject(((Пользователь) auth.getPrincipal()).getUsername()) .withClaim("роль", auth.getAuthorities().iterator().next().getAuthority()) .withExpiresAt(новая дата(System.currentTimeMillis() + AuthenticationConfigConstants.EXPIRATION_TIME)) .sign(Algorithm.HMAC256(AuthenticationConfigConstants.SECRET.getBytes())); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); ответ.getWriter().write( "{\"" + AuthenticationConfigConstants.HEADER_STRING + "\":\"" + AuthenticationConfigConstants.TOKEN_PREFIX + токен + "\"}" ); } } JwtAuthorization.java

пакет com.api.filter; импортировать java.io.IOException; импортировать java.util.Arrays; импортировать java.util.Collection; импортировать org.springframework.security.authentication.AuthenticationManager; импортировать org.springframework.security.authentication.UsernamePasswordAuthenticationToken; импортировать org.springframework.security.core.GrantedAuthority; импортировать org.springframework.security.core.authority.SimpleGrantedAuthority; импортировать org.springframework.security.core.context.SecurityContextHolder; импортировать org.springframework.security.web.authentication.www.BasicAuthenticationFilter; импортировать com.api.config.AuthenticationConfigConstants; импортировать com.auth0.jwt.JWT; импортировать com.auth0.jwt.algorithms.Algorithm; импортировать com.auth0.jwt.interfaces.DecodedJWT; импортировать jakarta.servlet.FilterChain; импортировать jakarta.servlet.ServletException; импортировать jakarta.servlet.http.HttpServletRequest; импортировать jakarta.servlet.http.HttpServletResponse; общественный класс JwtAuthorizationFilter расширяет BasicAuthenticationFilter { public JwtAuthorizationFilter (AuthenticationManager AuthenticationManager) { супер (Менеджер аутентификации); } @Override protected void doFilterInternal (запрос HttpServletRequest, ответ HttpServletResponse, цепочка FilterChain) выдает IOException, ServletException { Строковый заголовок = request.getHeader(AuthenticationConfigConstants.HEADER_STRING); if(header == null || !header.startsWith(AuthenticationConfigConstants.TOKEN_PREFIX)) { Chain.doFilter(запрос, ответ); System.out.println("Внутри JwtAuthorization doFilterInternal()"); возвращаться; } Аутентификация UsernamePasswordAuthenticationToken = getAuthentication (запрос); SecurityContextHolder.getContext().setAuthentication(аутентификация); Chain.doFilter(запрос, ответ); } частный UsernamePasswordAuthenticationToken getAuthentication (запрос HttpServletRequest) { Строковый токен = request.getHeader(AuthenticationConfigConstants.HEADER_STRING); если (токен! = ноль) { Строка пользователя = JWT.require(Algorithm.HMAC256(AuthenticationConfigConstants.SECRET.getBytes())) .строить() .verify(token.replace(AuthenticationConfigConstants.TOKEN_PREFIX, "")) .getSubject(); DecodedJWT проверить = JWT.require(Algorithm.HMAC256(AuthenticationConfigConstants.SECRET.getBytes())) .строить() .verify(token.replace(AuthenticationConfigConstants.TOKEN_PREFIX, "")); Строковое имя пользователя =verify.getSubject(); Строковая роль =verify.getClaim("роль").toString(); System.out.println(роль); если (пользователь! = ноль) { System.out.println("Внутри JwtAuthorization getAuthentication()"); вернуть новый UsernamePasswordAuthenticationToken (имя пользователя, ноль, getAuthorities (роль)); } вернуть ноль; } вернуть ноль; } публичная коллекция
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»