首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Olingo和JPA进行授权

使用Olingo和JPA进行授权
EN

Stack Overflow用户
提问于 2016-05-13 05:55:45
回答 2查看 1.8K关注 0票数 2

我正在使用JPA和Olingo来提供一些REST服务。我能够让基本实现与我的实体一起工作,类似于下面的示例:JPA Olingo Web App

但是,现在我尝试在连接到access表的地方添加授权,然后相应地过滤结果。我只是想知道是否有一种好的方法来做到这一点,而不必覆盖默认行为。我在这里看到了用于EDM的注释处理器Annotation Processor,但它似乎不太适合我们的模型。

我的问题是:有没有一种简单的方法来更改Olingo JPA处理器,以在默认情况下联接表和过滤实体,以便实现授权?这将要求我能够通过帐户来过滤,并限制所有的结果。

我还尝试了这里描述的预处理和后处理。然而,过滤需要在查询中完成,而不是在返回结果之后,因为Custom JPA Processor查询将返回太多的结果,并且转换数以千计的对象是冗长且成本高昂的。

到目前为止,我已经实现了一个CustomODataJPAProcessor。但是,它将要求我现在重写和覆盖org.apache.olingo.odata2.jpa.processor.core.access.data.JPAProcessorImpl#processmethod,并使用我想要的功能修改JPA查询。您将看到我实现了一个新的JPAProcessor,我在其中调用process并发送我的帐户。下面是我的CustomODataJPAProcessor的readEntitySet方法中的代码:

代码语言:javascript
复制
    /* Pre Process Step */
    preprocess( );
    List<String> accounts = new ArrayList<>();

    //This is what the original readEntitySet does
    //ODataJPAFactory.createFactory().getODataJPAAccessFactory().getODataJPAResponseBuilder(oDataJPAContext);

    //Using custom JPA Processor that I added
    jpaProcessor = new CustomJPAProcessor(this.oDataJPAContext);
    CustomJPAProcessor customJPAProcessor = (CustomJPAProcessor)jpaProcessor;
    List<Object> jpaEntities = customJPAProcessor.process(uriParserResultView, accounts);

    //What the docs want you to do http://olingo.apache.org/doc/odata2/tutorials/CustomODataJPAProcessor.html
    //java.util.List<Object> jpaEntities = jpaProcessor.process(uriParserResultView);

   /* Post Process Step */
    postProcess( );
EN

回答 2

Stack Overflow用户

发布于 2016-12-18 03:59:34

我不知道你是否还在努力。我现在正在解决这个问题。为了提供ODataJPAQueryExtensionEntityListener,此侦听器在buildQuery执行前一步由JPAQueryBuilder执行。

使用这个无状态侦听器,您可以替换buildQuery方法,这样就可以访问和更改包含jpqlStatement.toString查询的字符串JPQL ()。

我认为这比原生SQL更好。

再见多梅尼科

票数 1
EN

Stack Overflow用户

发布于 2020-06-17 20:37:21

Source of this tutorial

在这个 中,我已经使用了这个教程来创建JWT认证。我刚刚复制了全部内容以备将来之用,如果源链接不再有效,人们可以有机会访问它!

您需要根据您的用例调整示例,即必须更改包并且必须将库添加到pom.xml文件中。当然,您不需要添加HelloWorldController,但是将rest文件添加到应用程序中的类似文件夹中,它将在为odata.csv/$metadata或其他请求提供服务之前请求jwt令牌!

Spring Boot Security + JWT Hello World示例-启动

在本教程中,我们将开发一个Spring Boot应用程序,该应用程序使用JWT身份验证来保护公开的REST API。在本例中,我们将使用硬编码的用户值进行用户身份验证。在下一节中,我们将实现Spring Boot + JWT + MYSQL JPA来存储和获取用户凭证。只有在拥有有效的JSON Web Token (JWT)时,任何用户才能使用此API。

为了更好地理解,我们将分阶段开发该项目:

开发一个Spring Boot应用程序,该应用程序通过映射/hello公开一个简单的REST GET API。

为JWT配置Spring Security。使用映射/身份验证公开REST POST API,用户将使用该API获得有效的JSON Web令牌。然后,仅当接口/hello具有有效令牌时,才允许用户访问该接口

开发一个公开GET REST API的Spring Boot应用程序

Maven项目将如下所示:

pom.xml如下:

代码语言:javascript
复制
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.javainuse</groupId>
    <artifactId>spring-boot-jwt</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

</project>

创建一个用于公开GET REST API的Controller类-

代码语言:javascript
复制
package com.javainuse.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
    @RequestMapping({ "/hello" })
    public String firstPage() {
        return "Hello World";
    }
}

使用Spring Boot Annotation创建bootstrap类

代码语言:javascript
复制
package com.javainuse;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootHelloWorldApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootHelloWorldApplication.class, args);
    }
}

编译并将SpringBootHelloWorldApplication.java作为Java应用程序运行。

转到localhost:8080/hello

Spring Security和JWT配置

我们将配置Spring Security和JWT来执行2个操作-

  • Generating JWT使用映射/authenticate.公开POST 在传递正确的用户名和密码时,它将生成一个JSON Web -如果用户尝试使用映射/hello访问GET Token(JWT)
  • Validating。只有当请求具有有效JSON Web Token(JWT)

时,才允许访问

Maven项目将如下所示-

这些操作的顺序流如下所示:

生成JWT

验证JWT

添加Spring Security和JWT依赖项

代码语言:javascript
复制
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.javainuse</groupId>
    <artifactId>spring-boot-jwt</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>
    </dependencies>

</project>

定义application.properties。我们指定将用于散列算法的密钥。密钥与报头和有效负载相结合,以创建唯一的散列。只有在您拥有密钥的情况下,我们才能验证此哈希。

代码语言:javascript
复制
jwt.secret=javainuse

JwtTokenUtil

JwtTokenUtil负责执行像创建这样的JWT操作,而validation.It利用io.jsonwebtoken.Jwts来实现这一点。

代码语言:javascript
复制
package com.javainuse.config;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
@Component
public class JwtTokenUtil implements Serializable {
    private static final long serialVersionUID = -2550185165626007488L;
    public static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60;
    @Value("${jwt.secret}")
    private String secret;
    //retrieve username from jwt token
    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }
    //retrieve expiration date from jwt token
    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }
    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }
    //for retrieveing any information from token we will need the secret key
    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }
    //check if the token has expired
    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }
    //generate token for user
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        return doGenerateToken(claims, userDetails.getUsername());
    }
    //while creating the token -
    //1. Define  claims of the token, like Issuer, Expiration, Subject, and the ID
    //2. Sign the JWT using the HS512 algorithm and secret key.
    //3. According to JWS Compact Serialization(https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#section-3.1)
    //   compaction of the JWT to a URL-safe string 
    private String doGenerateToken(Map<String, Object> claims, String subject) {
        return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000))
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }
    //validate token
    public Boolean validateToken(String token, UserDetails userDetails) {
        final String username = getUsernameFromToken(token);
        return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
    }
}

JWTUserDetailsService

JWTUserDetailsService实现了Spring Security UserDetailsService接口。它覆盖了使用用户名从数据库中获取用户详细信息的loadUserByUsername。Spring Security Authentication Manager在验证用户提供的用户详细信息时,调用此方法从数据库获取用户详细信息。这里我们从一个硬编码的用户列表中获取用户的详细信息。此外,用户的密码使用BCrypt以加密格式存储。

代码语言:javascript
复制
package com.javainuse.service;
import java.util.ArrayList;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class JwtUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if ("javainuse".equals(username)) {
            return new User("javainuse", "$2a$10$slYQmyNdGzTn7ZLBXBChFOC9f6kFjAqPhccnP6DxlWXx2lPk1C3G6",
                    new ArrayList<>());
        } else {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }
    }
}

JwtAuthenticationController

使用JwtAuthenticationController公开POST API /authenticate。POST API在主体中获取用户名和密码-使用Spring Authentication Manager我们验证用户名并验证凭据有效,使用JWTTokenUtil创建password.If令牌并将其提供给客户端。

代码语言:javascript
复制
package com.javainuse.controller;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.javainuse.service.JwtUserDetailsService;
import com.javainuse.config.JwtTokenUtil;
import com.javainuse.model.JwtRequest;
import com.javainuse.model.JwtResponse;
@RestController
@CrossOrigin
public class JwtAuthenticationController {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private JwtUserDetailsService userDetailsService;
    @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception {
        authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());
        final UserDetails userDetails = userDetailsService
                .loadUserByUsername(authenticationRequest.getUsername());
        final String token = jwtTokenUtil.generateToken(userDetails);
        return ResponseEntity.ok(new JwtResponse(token));
    }
    private void authenticate(String username, String password) throws Exception {
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (DisabledException e) {
            throw new Exception("USER_DISABLED", e);
        } catch (BadCredentialsException e) {
            throw new Exception("INVALID_CREDENTIALS", e);
        }
    }
}

JwtRequest

这个类是用来存储我们从客户端收到的用户名和密码的。

代码语言:javascript
复制
package com.javainuse.model;
import java.io.Serializable;
public class JwtRequest implements Serializable {
    private static final long serialVersionUID = 5926468583005150707L;

    private String username;
    private String password;

    //need default constructor for JSON Parsing
    public JwtRequest()
    {

    }
    public JwtRequest(String username, String password) {
        this.setUsername(username);
        this.setPassword(password);
    }
    public String getUsername() {
        return this.username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return this.password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

JwtResponse

这是创建包含要返回给用户的JWT的响应所必需的类。

代码语言:javascript
复制
package com.javainuse.model;
import java.io.Serializable;
public class JwtResponse implements Serializable {
    private static final long serialVersionUID = -8091879091924046844L;
    private final String jwttoken;
    public JwtResponse(String jwttoken) {
        this.jwttoken = jwttoken;
    }
    public String getToken() {
        return this.jwttoken;
    }
}

JwtRequestFilter

JwtRequestFilter扩展了Spring Web Filter OncePerRequestFilter类。对于任何传入的请求,这个过滤器类都会被执行。它检查请求是否具有有效的JWT令牌。如果它具有有效的JWT令牌,则在上下文中设置身份验证,以指定对当前用户进行身份验证。

代码语言:javascript
复制
package com.javainuse.config;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.javainuse.service.JwtUserDetailsService;
import io.jsonwebtoken.ExpiredJwtException;
@Component
public class JwtRequestFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        final String requestTokenHeader = request.getHeader("Authorization");
        String username = null;
        String jwtToken = null;
        // JWT Token is in the form "Bearer token". Remove Bearer word and get
        // only the Token
        if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
            jwtToken = requestTokenHeader.substring(7);
            try {
                username = jwtTokenUtil.getUsernameFromToken(jwtToken);
            } catch (IllegalArgumentException e) {
                System.out.println("Unable to get JWT Token");
            } catch (ExpiredJwtException e) {
                System.out.println("JWT Token has expired");
            }
        } else {
            logger.warn("JWT Token does not begin with Bearer String");
        }
        // Once we get the token validate it.
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(username);
            // if token is valid configure Spring Security to manually set
            // authentication
            if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                usernamePasswordAuthenticationToken
                        .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // After setting the Authentication in the context, we specify
                // that the current user is authenticated. So it passes the
                // Spring Security Configurations successfully.
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        chain.doFilter(request, response);
    }
}

JwtAuthenticationEntryPoint

这个类将扩展Spring的AuthenticationEntryPoint类并覆盖它的方法class。它拒绝每个未经验证的请求,并发送错误代码401

代码语言:javascript
复制
package com.javainuse.config;
import java.io.IOException;
import java.io.Serializable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
    private static final long serialVersionUID = -7858869558953243875L;
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }
}

WebSecurityConfig

这个类扩展了WebSecurityConfigurerAdapter,它是一个方便的类,允许对WebSecurity和HttpSecurity进行自定义。

代码语言:javascript
复制
package com.javainuse.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    @Autowired
    private UserDetailsService jwtUserDetailsService;
    @Autowired
    private JwtRequestFilter jwtRequestFilter;
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // configure AuthenticationManager so that it knows from where to load
        // user for matching credentials
        // Use BCryptPasswordEncoder
        auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // We don't need CSRF for this example
        httpSecurity.csrf().disable()
                // dont authenticate this particular request
                .authorizeRequests().antMatchers("/authenticate").permitAll().
                // all other requests need to be authenticated
                anyRequest().authenticated().and().
                // make sure we use stateless session; session won't be used to
                // store user's state.
                exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // Add a filter to validate the tokens with every request
        httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

启动Spring引导应用程序

  • 生成JSON Web令牌-
  • 使用url localhost:8080/authenticate创建POST请求。正文应具有有效的用户名和密码。在我们的例子中,用户名是password.

,密码是javainuse

  • 验证JSON Web令牌
  • 尝试在标头中使用上面生成的令牌访问url localhost:8080/hello,如下所示

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37198106

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档