Size: a a a

Spring Framework and more

2020 June 21

AE

Alexandr Emelyanov in Spring Framework and more
Vladislav Gerasimov
использую spring data repository
также там можно и с помощью jpa specification запросы строить
Исходный вопрос смотрите о чем
источник

AE

Alexandr Emelyanov in Spring Framework and more
Waldemar Tsiamruk
Может если вендор апи
М?
источник

AE

Alexandr Emelyanov in Spring Framework and more
Waldemar Tsiamruk
Может если вендор апи
Какое вендор при имеется ввиду
источник

WT

Waldemar Tsiamruk in Spring Framework and more
ну тот же hql как вы говорите)
источник

WT

Waldemar Tsiamruk in Spring Framework and more
именно hibernate api :)
источник

WT

Waldemar Tsiamruk in Spring Framework and more
источник

WT

Waldemar Tsiamruk in Spring Framework and more
читал что умеет в такое и EclipseLink, но не найду примера
источник

AE

Alexandr Emelyanov in Spring Framework and more
Ну вот, начиная с 5.1 считай
источник

WT

Waldemar Tsiamruk in Spring Framework and more
или с 2 точка какой-то версии EclipseLink
источник

AE

Alexandr Emelyanov in Spring Framework and more
Spring data существует сильно давно что бы hql можно было на 5.1 писать
источник

WT

Waldemar Tsiamruk in Spring Framework and more
источник

WT

Waldemar Tsiamruk in Spring Framework and more
вот criteria, но блин это ж получается гуглится) зачем спрашивать)
источник

WT

Waldemar Tsiamruk in Spring Framework and more
хотя мб не работает в статье подход описанный :)
источник

AS

Anatoly Shirokov in Spring Framework and more
Настраиваю HttpSecurity для доступа к вебсервису:
        http
        .csrf().disable()
        .authorizeRequests()
         .antMatchers("/ws/**").hasRole("USER")
        .and()
         .httpBasic().authenticationEntryPoint(authEntryPoint)
        .and()
         .sessionManagement()
         .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        ;
при попытке получить wsdl:
>curl --silent --verbose -u tom:123 http://localhost:18080/ws/info/info.wsdl
* Connected to localhost (::1) port 18080 (#0)
* Server auth using Basic with user 'tom'
> POST /ws/info HTTP/1.1
> Host: localhost:18080
> Authorization: Basic dG9tOjEyMw==
> User-Agent: curl/7.55.1
> Accept: */*
> content-type: text/xml;charset=utf-8
> Content-Length: 310
>
} [310 bytes data]
* upload completely sent off: 310 out of 310 bytes
< HTTP/1.1 403
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Content-Type: application/json
< Transfer-Encoding: chunked
< Date: Sun, 21 Jun 2020 20:18:53 GMT
<
{ [115 bytes data]
* Connection #0 to host localhost left intact
{"timestamp":"2020-06-21T20:18:53.466+00:00","status":403,"error":"Forbidden","message":"","path":"/ws/info"}

Почему 403?

В логе вижу, что аутентификация проходит:
2020-06-21 23:18:53.465  INFO 19544 --- [io-18080-exec-4] r.r.ws.WebAuthenticationEntryPoint       : Authentication succeeded for tom, granted USER role

Если заменить
.antMatchers("/ws/**").hasRole("USER")

на
.anyRequest().authenticated()

wsdl получаю
источник

PG

Pavel Gromov in Spring Framework and more
роль USER или ROLE_USER?
источник

PG

Pavel Gromov in Spring Framework and more
и если есть возможность на ентри поинт глянуть
источник

AS

Anatoly Shirokov in Spring Framework and more
Pavel Gromov
и если есть возможность на ентри поинт глянуть
@Component
public class WebAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
 private static final Logger log = LoggerFactory.getLogger(WebAuthenticationEntryPoint.class);

 public WebAuthenticationEntryPoint() {
   log.info("Constructed");
 }
 
 @Override
 public void commence(HttpServletRequest request, HttpServletResponse response,
     AuthenticationException authException) throws IOException {
   super.commence(request, response, authException);
 }
 @Override
 public void afterPropertiesSet() {
       setRealmName("mydomain");
       super.afterPropertiesSet();
 }
}
источник

AS

Anatoly Shirokov in Spring Framework and more
Pavel Gromov
роль USER или ROLE_USER?
USER:
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

 private static final Logger log = LoggerFactory.getLogger(WebAuthenticationEntryPoint.class);
 private static List<User> users = new ArrayList();

 public CustomAuthenticationProvider() {
   log.info("Constructed");
   users.add(new User("tom", "123", "USER"));
 }

 @Override
 public Authentication authenticate(Authentication authentication) throws AuthenticationException {

   String name = authentication.getName();
   Object credentials = authentication.getCredentials();
   if (!(credentials instanceof String)) {
     // Возращаем null, если мы не можем выполнить аутентификация
     return null;
   }
   String password = credentials.toString();
   Optional<User> userOptional = users.stream().filter(u -> u.match(name, password)).findFirst();
   if (!userOptional.isPresent()) {
     log.error("Authentication failed for {}", name);
     throw new BadCredentialsException("Authentication failed for " + name);
   }
   String role = userOptional.get().role;
   log.info("Authentication succeeded for {}, granted {} role", name, role);
   return new UsernamePasswordAuthenticationToken(name, password,
       Arrays.asList(new SimpleGrantedAuthority(role)));
 }

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

 private static class User {
   private String name;
   private String password;
   private String role;

   public User(String name, String password, String role) {
     this.name = name;
     this.password = password;
     this.role = role;
   }

   public boolean match(String name, String password) {
     return this.name.equals(name) && this.password.equals(password);
   }
 }
}
источник

PG

Pavel Gromov in Spring Framework and more
SimpleGrantedAuthority это не роль, по этому нужно добавить префикс ROLE_
источник

PG

Pavel Gromov in Spring Framework and more
либо в конфигурации поменять .hasRole на hasAuthority
источник