JERSEY - 将javax.ws.rs.core.Response作为JSON对象返回,并带有错误:...或令牌:

问题描述 投票:0回答:1

编辑:有没有办法返回一个简单的对象,该对象具有:

  • 代币
  • 错误
  • 错误和细节

......无需创建新对象。什么是最有效和最容易理解的方法?

我正在尝试创建一个@Consumes(MediaType.APPLICATION_JSON)(包含登录凭据:用户名,密码,消费者(布尔))的登录服务。

如果凭证有效,我想在前端返回一个令牌,以及一个响应代码OK / 200;像这个JSON对象:

{"token":"aAKGKas211"}

否则我对每个案例都有特定的错误,我想返回一个不同的RESPONSE CODE,它看起来像这样:

{"error":"Invalid username or password"}

我试图将一个字符串错误(=“无效的用户名或密码”)添加到Response.Status.NOT_ACCEPTABLE).entity(错误),但我得到的字符串不是作为JSON对象的字符串..

这是我的代码的样子:

@POST
@Path("/login")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response login(@Context HttpServletRequest req, LoginInfo loginInfo) {
    CouponClientFacade facade = null;
    String token = null, error = null;

    // validate the REQUESTer's token, if he is already logged in return ERROR RESPONSE.
    System.out.println(loginInfo);
    System.out.println(req.getSession().getId());
    if (loginInfo == null)
        return Response.ok("Test").build();
    if (validateCredentials(loginInfo))
        return Response.status(Response.Status.NOT_ACCEPTABLE).entity("Invalid username or password").build();


    try { // Try to login into administrator
        facade = ClientType.ADMIN.login(loginInfo.getUsername(), loginInfo.getPassword());
    } catch (Exception E) { // Couldn't login into administrator
        try {
            if (loginInfo.isCustomer()) // Try to login into CUSTOMER account
                facade = ClientType.CUSTOMER.login(loginInfo.getUsername(), loginInfo.getPassword());
            else // Try to login into COMPANY account
                facade = ClientType.COMPANY.login(loginInfo.getUsername(), loginInfo.getPassword());

        } catch (BadUsernamePassword e) {
            return Response.status(Response.Status.FORBIDDEN).entity(error=e.getMessage()).build();
        } catch (UnexpectedError e) {
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error=e.getMessage()).build();
        }
    }
    if (facade != null) {
        token = SessionManager.generateToken(req.getSession().getId(), facade);
        return Response.ok(token).build();
    } else return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error="111").build();
}

编辑:

java json rest jaxb jersey
1个回答
1
投票

在“授权”标题中传递您的令牌

基本身份验证为此问题提供了解决方案,但不是很安全。使用基本身份验证,客户端使用HTTP [授权]标头为每个请求发送它的Base64编码凭据。这意味着每个请求都独立于其他请求,并且服务器可能/不维护客户端的任何状态信息,这对于可伸缩性的观点是有利的。

HTTPS上的一句话:对于任何类型的安全实施,从基本身份验证到完全成熟的OAuth2实现,HTTPS都是必须的。如果没有HTTPS,无论您的实施是什么,安全性都很容易受到损害。

String plainClientCredentials="myusername:mypassword";
String base64ClientCredentials = new String(Base64.encodeBase64(plainClientCredentials.getBytes()));

HttpHeaders headers = getHeaders();
headers.add("Authorization", "Basic " + base64ClientCredentials);

这可能反过来产生类似的东西:

Authorization : Basic bXktdHJ1c3FOO1jbGllbnQ6c2VjcmV0...

基本身份验证和Spring安全性通过两个步骤,您可以在Spring Security配置中启用基本身份验证。 1.配置httpBasic:配置HTTP基本身份验证。 [XML中的http-basic] 2.使用BasicAuthenticationEntryPoint配置身份验证入口点:如果身份验证失败[无效/丢失凭据],将触发此入口点。这非常重要,因为我们不希望[Spring Security默认行为]在身份验证失败时重定向到登录页面[我们没有登录页面]。

下面显示的是具有httpBasic和入口点设置的完整Spring Security配置。

package com.websystique.springmvc.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
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;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private static String REALM="MY_TEST_REALM";

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("bill").password("abc123").roles("ADMIN");
        auth.inMemoryAuthentication().withUser("tom").password("abc123").roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

      http.csrf().disable()
        .authorizeRequests()
        .antMatchers("/user/**").hasRole("ADMIN")
        .and().httpBasic().realmName(REALM).authenticationEntryPoint(getBasicAuthEntryPoint())
        .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);//We don't need sessions to be created.
    }

    @Bean
    public CustomBasicAuthenticationEntryPoint getBasicAuthEntryPoint(){
        return new CustomBasicAuthenticationEntryPoint();
    }

    /* To allow Pre-flight [OPTIONS] request from browser */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
    }
}

和实际的入口点,如果身份验证失败将触发。您可以自定义它以发送自定义内容作为响应。

package com.websystique.springmvc.security;

import java.io.IOException;
import java.io.PrintWriter;

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

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;

public class CustomBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

    @Override
    public void commence(final HttpServletRequest request, 
            final HttpServletResponse response, 
            final AuthenticationException authException) throws IOException, ServletException {
        //Authentication failed, send error response.
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() + "");

        PrintWriter writer = response.getWriter();
        writer.println("HTTP Status 401 : " + authException.getMessage());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        setRealmName("MY_TEST_REALM");
        super.afterPropertiesSet();
    }
}

这就是配置基本安全性所需的全部内容。现在让我们使用我们优秀的旧REST API查看所有操作

REST API Simple Spring REST API,为用户提供服务。客户端可以使用符合REST样式的标准HTML动词执行CRUD操作。

package com.websystique.springmvc.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
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 org.springframework.web.util.UriComponentsBuilder;

import com.websystique.springmvc.model.User;
import com.websystique.springmvc.service.UserService;

@RestController
public class HelloWorldRestController {

    @Autowired
    UserService userService;  //Service which will do all data retrieval/manipulation work


    //-------------------Retrieve All Users--------------------------------------------------------

    @RequestMapping(value = "/user/", method = RequestMethod.GET)
    public ResponseEntity<List<User>> listAllUsers() {
        List<User> users = userService.findAllUsers();
        if(users.isEmpty()){
            return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
        }
        return new ResponseEntity<List<User>>(users, HttpStatus.OK);
    }


    //-------------------Retrieve Single User--------------------------------------------------------

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE,MediaType.APPLICATION_XML_VALUE})
    public ResponseEntity<User> getUser(@PathVariable("id") long id) {
        System.out.println("Fetching User with id " + id);
        User user = userService.findById(id);
        if (user == null) {
            System.out.println("User with id " + id + " not found");
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }



    //-------------------Create a User--------------------------------------------------------

    @RequestMapping(value = "/user/", method = RequestMethod.POST)
    public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder) {
        System.out.println("Creating User " + user.getName());

        if (userService.isUserExist(user)) {
            System.out.println("A User with name " + user.getName() + " already exist");
            return new ResponseEntity<Void>(HttpStatus.CONFLICT);
        }

        userService.saveUser(user);

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
    }


    //------------------- Update a User --------------------------------------------------------

    @RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
    public ResponseEntity<User> updateUser(@PathVariable("id") long id, @RequestBody User user) {
        System.out.println("Updating User " + id);

        User currentUser = userService.findById(id);

        if (currentUser==null) {
            System.out.println("User with id " + id + " not found");
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }

        currentUser.setName(user.getName());
        currentUser.setAge(user.getAge());
        currentUser.setSalary(user.getSalary());

        userService.updateUser(currentUser);
        return new ResponseEntity<User>(currentUser, HttpStatus.OK);
    }

    //------------------- Delete a User --------------------------------------------------------

    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<User> deleteUser(@PathVariable("id") long id) {
        System.out.println("Fetching & Deleting User with id " + id);

        User user = userService.findById(id);
        if (user == null) {
            System.out.println("Unable to delete. User with id " + id + " not found");
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }

        userService.deleteUserById(id);
        return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
    }


    //------------------- Delete All Users --------------------------------------------------------

    @RequestMapping(value = "/user/", method = RequestMethod.DELETE)
    public ResponseEntity<User> deleteAllUsers() {
        System.out.println("Deleting All Users");

        userService.deleteAllUsers();
        return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.