简体   繁体   English

将权限和用户主体从 rest 客户端传递到服务器 spring 启动

[英]Passing authorities and user principal from rest client to server spring boot

I have to call one secured endpoint from rest client and at the controller side it require the authorities and user principal information to be sent from client.我必须从 rest 客户端调用一个安全端点,在 controller 端,它需要从客户端发送权限和用户主体信息。

 String  endpoint="http://localhost:8096/polygons/34";
           // endpoint="https://dop-int.edosdp.ericsson.se/polygon-manager/polygons/34";
            HttpHeaders headers = new HttpHeaders();
            headers.setBasicAuth("mahi", "ChangeM6");
            headers.setConnection("keep-alive");       
             HttpEntity<String> httpEntity = new HttpEntity<String>(headers);       
            ResponseEntity<Long> exchange = restTemplate.exchange(endpoint,HttpMethod.GET, httpEntity, Long.class);    

how can send at least one role(ADMIN or GUEST_USER) information from client.如何从客户端发送至少一个角色(ADMIN 或 GUEST_USER)信息。 IS there any way I can wrap up all user info in a dummy session and send it to the serer.有什么办法可以将所有用户信息包装在虚拟 session 中并将其发送给服务器。

Thanks, Mahi谢谢,麻希

No. It's a bad idea for the client to modify any kind of session information including cookies. Only the server should be allowed to do that.不可以。客户端修改任何类型的 session 信息(包括 cookies)都是一个坏主意。只应允许服务器这样做。

Since your requirement is to check for user role on a specific url, you can set a custom request header and check for it within the controller method itself:由于您的要求是检查特定 url 上的用户角色,您可以设置自定义请求 header 并在 controller 方法本身中检查它:

Example code:示例代码:

@GetMapping("/polygons")
public String getPolygons(HttpServletRequest request) {     
    String userRole = request.getHeader("user-role");
    if(userRole != null && userRole.toLowerCase().equals("admin")) {
        System.out.print("Role provided: " + userRole);     
        // ...
        return "some-data";
    }           
    
    System.out.print("Role not provided!");
    return "error";
}

邮递员客户端 - 设置自定义标题

You could also set the user role in the request body for a post request.您还可以在请求正文中为发布请求设置用户角色。

public class RequestParams {
    private String userRole;
    // ...
}       

@PostMapping("/polygons")
public String getPolygons(@RequestBody RequestParams requestParams) {
    String userRole = requestParams.getUserRole();
    if(userRole != null && userRole.toLowerCase().equals("admin")) {
        System.out.print("Role provided: " + userRole);     
        // ...
        return "some-data";
    }           
    
    System.out.print("Role not provided!");
    return "error";
}

设置 POST 请求体

If your requirement is to check for the user role on multiple urls then you should consider writing a servlet filter.如果您的要求是检查多个 url 上的用户角色,那么您应该考虑编写一个 servlet 过滤器。

EDIT:编辑:

I think I too faced a similar situation in the past.我想我过去也遇到过类似的情况。 I ended up using apache's httpclient library instead of resttemplate.我最终使用了 apache 的 httpclient 库而不是 resttemplate。

Here's some sample code:这是一些示例代码:

private List<OrganizationDTO> getUserOrgUnits(String loggedInUserId, String token) {
    List<OrganizationDTO> userList = new ArrayList<OrganizationDTO>();      

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(getUserOrgUnitsApiURL());
    try {
        // Setting header
        httpGet.setHeader("Authorization", "Bearer " + token);
        httpGet.setHeader("Content-type", "application/json");
        // Setting custom header
        httpGet.setHeader(USERID_HEADER_NAME, loggedInUserId);
        
        CloseableHttpResponse response = httpClient.execute(httpGet);
        String  result = EntityUtils.toString(response.getEntity());
        
        JsonNode node = null;
        ObjectMapper mapper = new ObjectMapper();
        node = mapper.readTree(result);
        Iterable<JsonNode> list = node.path("data");            
        for (JsonNode jsonNode : list) {
            OrganizationDTO dto = mapper.treeToValue(jsonNode, OrganizationDTO.class);
            userList.add(dto);
        }
    } catch (Exception e) {
        log.error("getUserOrgUnits: Exception.");
        e.printStackTrace();
    }                                       
    return userList;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将主要用户从一个 spring boot 微服务传递到另一个 springboot 微服务 - Passing principal user from one spring boot microservice to other springboot microservice 在Spring Boot OAuth 2中无法从主体对象获取用户详细信息 - Not able to get user details from principal object in Spring boot OAuth 2 从 JWT 令牌获取 Spring Boot 资源服务器中的主体 - Get principal in Spring Boot resource server from JWT token Spring Boot在Rest Client中授权用户,但未在浏览器中授权用户(Rest授权) - Spring Boot Authorizes User In Rest Client, But Not In Browser (Rest Authorization) Spring 引导资源服务器主体名称 - Spring boot resource server principal name Spring 启动 Oauth 安全性 - 客户端凭据授予类型中主体中的用户(自定义信息)信息 - Spring boot Oauth security - User(custom info) info in the principal in Client Credentials grant type Spring 启动 - rest 客户端来自 rest Z594C103F2C6E04C3D8AB059F0310E 接口C - Spring boot - rest client from rest controller interface 从 Principal 中提取数据 Java Spring Boot - Extract data from Principal in Java Spring Boot Spring Boot-具有自签名证书的客户端服务器REST API - Spring Boot - client server REST API with self-signed certificate Spring 启动 oauth2:无 userInfo 端点 - 如何直接在客户端从 JWT 访问令牌加载身份验证(主体) - Spring boot oauth2: No userInfo endpoint - How to load the authentication (Principal) from the JWT access token directly in the client
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM