标签: spring-rest

具有跨源资源共享(CORS)的AngularJS spring安全登录/注销

问题陈述:我的UI应用程序在9000端口(grunt项目)上运行,我的服务器端spring引导项目在8421端口上运行.除登录和注销外,我能够从我的UI应用程序中点击所有URL.请告诉我如何使用CORS配置spring security登录和注销.

App.js

  $scope.login = function() {
        $http.post('http://localhost:8421/login', $.param($scope.credentials), {
          headers : {
            'content-type' : 'application/x-www-form-urlencoded'
          }
        }).success(function() {
          console.log('login success');
          });
        }).error(function() {
          console.log('login error');
        });
      };
Run Code Online (Sandbox Code Playgroud)

SecurityConfiguration.java

public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

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

        http.addFilterBefore(new SimpleCORSFilter(), ChannelProcessingFilter.class)
        .authorizeRequests().antMatchers("/rest/**").permitAll()
        .and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        .logoutSuccessUrl("/index.html")        
        .and().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)       
        .and().formLogin().successHandler(authenticationSuccessHandler)
        .and().formLogin().failureHandler(authenticationFailureHandler)         
        .and().csrf().disable();
    }

@Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }
}
Run Code Online (Sandbox Code Playgroud)

SimpleCORSFilter.java

public class SimpleCORSFilter implements Filter {
@Override
    public void doFilter(ServletRequest req, ServletResponse …
Run Code Online (Sandbox Code Playgroud)

spring-security cors angularjs angularjs-http spring-rest

5
推荐指数
1
解决办法
4289
查看次数

在 Spring Boot 中有条件地从 @RestController 返回 JSON 和 (HTML) 模板

大多数类似的问题似乎都有与我\xe2\x80\x99m 相反的问题。

\n\n

I\xe2\x80\x99m 使用以下命令构建基于 Spring Boot 的 Web 应用程序@RestController. JSON 响应运行良好,但现在我想支持通过模板(特别是 Thymeleaf)返回 HTML。所有示例都显示了这样的构建方法:

\n\n
@RequestMapping(method = RequestMethod.GET)\nString index()\n{\n    return "index";\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

只要 it\xe2\x80\x99s 中的类用@Controller. 如果我用 进行注释@RestController,我会得到文字字符串“index”。这是有道理的,因为@RestController意味着@ResponseBody.

\n\n

我对此有一些一般性的问题\xe2\x80\xa6

\n\n
    \n
  • @Controller使用和明确的做法是否正确@ResponseBody在旨在返回 JSON 的方法上

  • \n
  • 我担心我的 Controller 类会变得相当大,因为我\xe2\x80\x99ll 对大多数 GET 方法有两种实现(一种返回 HATEOAS JSON,一种返回模型中包含更多内容的 HTML)。是否有推荐的做法来分解这个?

  • \n
\n\n

感谢您的建议。谢谢!

\n

spring spring-mvc spring-boot spring-rest

5
推荐指数
1
解决办法
5008
查看次数

Spring RestTemplate (setBufferRequestBody as false) 不喜欢包含 InputStream 对象的 MultiValueMap 请求体

我正在尝试以服务到服务的方式转发一个非常大的 csv 格式的文件。

因此,用户上传了一个非常大的 csv 文件(几个 GB),后端接收该文件作为 Spring 的MultipartFile抽象(我的版本是spring-web-4.3.3.RELEASE)。

之后,我MultipartFile使用RestTemplate. 一切工作正常,如果setBufferRequestBodytrue在要求的工厂,但如预期,它与内存不足的错误炸毁内存文件的字节被写入之前内部缓冲。但是,当我设置setBufferRequestBody为 时false,出现以下异常。

我发现 Spring 代理我的自定义请求工厂InterceptingClientHttpRequest,然后在内部将其委托给我的自定义请求工厂:

java.lang.UnsupportedOperationException: getBody not supported
    at org.springframework.http.client.HttpComponentsStreamingClientHttpRequest.getBodyInternal(HttpComponentsStreamingClientHttpRequest.java:84)
    at org.springframework.http.client.AbstractClientHttpRequest.getBody(AbstractClientHttpRequest.java:47)
    at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:91)
    at org.springframework.cloud.netflix.metrics.MetricsClientHttpRequestInterceptor.intercept(MetricsClientHttpRequestInterceptor.java:65)
    at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:85)
    at org.springframework.http.client.InterceptingClientHttpRequest.executeInternal(InterceptingClientHttpRequest.java:69)
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:619)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:595)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:516)
    at org.springframework.web.client.RestTemplate$$FastClassBySpringCGLIB$$aa4e9ed0.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
    at org.keycloak.adapters.springsecurity.client.KeycloakRestTemplate$$EnhancerBySpringCGLIB$$596ee8a2.exchange(<generated>)
    at us.deloitteinnovation.cfsa.service.dawb.impl.DatafileServiceImpl.doUploadInternal(DatafileServiceImpl.java:131)
    at us.deloitteinnovation.cfsa.service.dawb.impl.DatafileServiceImpl.uploadDataFile(DatafileServiceImpl.java:88)
    at …
Run Code Online (Sandbox Code Playgroud)

spring resttemplate spring-boot spring-rest

5
推荐指数
1
解决办法
3887
查看次数

XmlElement(name =“ custom_name”)在与其余服务集成的Spring Boot中不起作用

我几乎是休息服务世界的新手,在这里我试图更改输出xml中显示的字段名称。

不确定,如果我遵循正确的方法,任何帮助都是一件好事。

Activity.java

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Activity {

    private int activityId;
    private int duration;
    private String  description;


    public Activity(int activityId, int duration, String description) {
        super();
        this.activityId = activityId;
        this.duration = duration;
        this.description = description;
    }

    @XmlElement(name="actvID")
    public int getActivityId() {
        return activityId;
    }
    public void setActivityId(int activityId) {
        this.activityId = activityId;
    }
    public int getDuration() {
        return duration;
    }
    public void setDuration(int duration) {
        this.duration = duration;
    }
    public String …
Run Code Online (Sandbox Code Playgroud)

rest jaxb spring-boot spring-restcontroller spring-rest

5
推荐指数
2
解决办法
875
查看次数

如何将路径变量映射到 spring-rest 中的实体

我在 Spring-RS 中得到了一些 REST 端点,它使用实体 id 作为路径变量。大多数时候,该方法所做的第一件事是使用 id 检索实体。有没有办法自动将 id 映射到实体,仅将实体作为方法参数?

现在的情况 :

@RequestMapping(path="/{entityId})
public void method(@PathVariable String entityId) {
    Entity entity = entityRepository.findOne(entityId);
    //Do some work
}
Run Code Online (Sandbox Code Playgroud)

我想要什么:

@RequestMapping(path="/{entityId})
public void method(@PathVariable Entity entityId) {
    //Do some work
}
Run Code Online (Sandbox Code Playgroud)

java spring-restcontroller spring-rest

5
推荐指数
1
解决办法
3021
查看次数

Spring Data mongodb聚合管道的分页结果

我在对聚合管道的结果进行分页时遇到了一些麻烦。在查看了In spring data mongodb 如何实现分页进行聚合后,我想出了一个感觉像 hacky 的解决方案。我首先执行匹配查询,然后按我搜索的字段分组,并对结果进行计数,将值映射到一个私有类:

private long getCount(String propertyName, String propertyValue) {
    MatchOperation matchOperation = match(
        Criteria.where(propertyName).is(propertyValue)
    );
    GroupOperation groupOperation = group(propertyName).count().as("count");
    Aggregation aggregation = newAggregation(matchOperation, groupOperation);
    return mongoTemplate.aggregate(aggregation, Athlete.class, NumberOfResults.class)
        .getMappedResults().get(0).getCount();
}

private class NumberOfResults {
    private int count;

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,我就能够为我返回的页面对象提供一个“总”值:

public Page<Athlete> findAllByName(String name, Pageable pageable) {
    long total = getCount("team.name", name);
    Aggregation aggregation = getAggregation("team.name", name, pageable); …
Run Code Online (Sandbox Code Playgroud)

spring-data-mongodb spring-boot spring-restcontroller spring-rest

5
推荐指数
1
解决办法
5560
查看次数

spring CORS 和 angular 不起作用:HTTP 状态代码 403 错误

我是 angular 和 spring-security 的新手。尝试使用基本身份验证从 angular 登录表单页面登录到其余端点时,我遇到了 CORS 问题。我的 Angular 代码在http://localhost:4200 上运行,其余端点在http://localhost:8181 上。我的角度登录表单尝试向我在登录控制器中指定的http://localhost:8181/token发出请求。即使我在服务器端添加了 cors 配置,我还是收到了这个错误:-

无法加载http://localhost:8181/token:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。来源 ' http://localhost:4200因此,不允许访问 '。响应具有 HTTP 状态代码 403。

(角度)login.service.ts:-

@Injectable()
export class LoginService {
  constructor(private http: Http) {}

  sendCredential(username: string, password: string) {
    const url = 'http://localhost:8181/token';
    const encodedCredential = username + ':' + password;
    const basicHeader = 'Basic ' + btoa(encodedCredential);
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-wwww-form-urlencoded');
    headers.append('Authorization' ,  basicHeader);
    const opts = new RequestOptions({headers: …
Run Code Online (Sandbox Code Playgroud)

java spring spring-rest angular

5
推荐指数
1
解决办法
2万
查看次数

如何使用 zuul 代理过滤器路由到外部 url

我有一个外部 url,我想通过 zuul 过滤器传递一些请求头来启动应用程序。任何人都可以帮我解决这个问题。在我的自定义预过滤器中,我写了这个:

 @Component
public class CustomFilters extends ZuulFilter {

    public static final Logger logger = LoggerFactory.getLogger(CustomFilters.class);


    @Override
    public String filterType() {
        return "route";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {

        return true;
    }

    @Override
    public Object run() {
        logger.info("executing run ");
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.addZuulRequestHeader("x-forwarded-host", "<external url>");
        ctx.addZuulRequestHeader("x-forwarded-proto", "https");
        ctx.addZuulRequestHeader("x-forwarded-port", "8800");
        ctx.addZuulRequestHeader("key", "id);

        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

app.properties:

ribbon.eureka.enabled=false
server.port=8080
zuul.routes.books.sensitive-headers=
zuul.routes.books.path = /books/
zuul.routes.books.url = <ext url>
Run Code Online (Sandbox Code Playgroud)

示例应用程序:这给了我一个 rest …

spring-boot netflix-zuul spring-rest

5
推荐指数
1
解决办法
3725
查看次数

MockRestServiceServer:如何用主体模拟POST调用?

我正在尝试MockRestServiceServer通过以下方式模拟POST方法:

MockRestServiceServer server = bindTo(restTemplate).build();
server.expect(requestTo("/my-api"))
        .andExpect(method(POST))
        .andRespond(withSuccess(expectedResponce, APPLICATION_JSON));
Run Code Online (Sandbox Code Playgroud)

问题:如何在此设置中验证请求正文?

我浏览了文档和一些示例,但仍然不知道如何完成。

java junit spring spring-boot spring-rest

5
推荐指数
1
解决办法
690
查看次数

如何在不使用 API Gateway 的情况下使用 AWS Cognito 进行自定义 Spring REST API 授权

场景:
我将在任何 EC2 中运行 Spring boot REST API 应用程序并公开多个 API,并且我没有为它们使用 AWS API Gateway。
我需要多个用户来访问具有不同角色(Admin、WriteUser、ReadUser)的多个 API。
我可以在 Cognito 用户池中创建用户和组,并且可以在 IAM 中拥有多个角色。

如何配置 AWS Cognito 的 UserPool 和 IdentityPool 以根据用户角色授权不同的 API 访问?是否有任何方法可以在不使用 API 网关的情况下在策略(与 IdentityPool/资源服务器关联)中定义此类“基于角色的 API 允许规则”。

提前致谢。

api authorization amazon-cognito spring-rest

5
推荐指数
1
解决办法
2309
查看次数