在本文中,我们将详细介绍SpringSecurity吃AngularJSPOST请求的各个方面,并为您提供关于springsecuritypostman的相关解答,同时,我们也将为您带来关于Adala
在本文中,我们将详细介绍Spring Security吃AngularJS POST请求的各个方面,并为您提供关于spring security postman的相关解答,同时,我们也将为您带来关于Adal angular spring security azure 广告集成、Angular 2 http.post不适用于Spring Security、Angular 2,Spring boot,spring security,登录表单、Angular.Js + Spring Security 的权限控制使用的有用知识。
本文目录一览:- Spring Security吃AngularJS POST请求(spring security postman)
- Adal angular spring security azure 广告集成
- Angular 2 http.post不适用于Spring Security
- Angular 2,Spring boot,spring security,登录表单
- Angular.Js + Spring Security 的权限控制使用
Spring Security吃AngularJS POST请求(spring security postman)
在使用spring security自定义登录表单时,我从UI传递的参数无法在HttpServletRequest中访问。
class StatelessLoginFilter extends AbstractAuthenticationProcessingFilter { private final TokenAuthenticationService tokenAuthenticationService; private final CustomJDBCDaoImpl userDetailsService; protected StatelessLoginFilter(String urlMapping, TokenAuthenticationService tokenAuthenticationService, CustomJDBCDaoImpl userDetailsService, AuthenticationManager authManager) { super(new AntPathRequestMatcher(urlMapping)); this.userDetailsService = userDetailsService; this.tokenAuthenticationService = tokenAuthenticationService; setAuthenticationManager(authManager); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { final UsernamePasswordAuthenticationToken loginToken = new UsernamePasswordAuthenticationToken( request.getAttribute("email").toString(), request.getAttribute("password").toString()); return getAuthenticationManager().authenticate(loginToken); } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException { final UserDetails authenticatedUser = userDetailsService.loadUserByUsername(authentication.getName()); final UserAuthentication userAuthentication = new UserAuthentication(authenticatedUser); tokenAuthenticationService.addAuthentication(response, userAuthentication); SecurityContextHolder.getContext().setAuthentication(userAuthentication); }}
在AttemptAuthentication方法中,请求未使用以下代码从POST请求传递的属性:
var request = $http.post(''/verifyUser'', {email: ''user'', password: ''user'',_csrf: $cookies[''XSRF-TOKEN'']})
我尝试使用调试器控制台对其进行跟踪,发现有效负载中填充了我转发的元素。
{“电子邮件”:“用户”,“密码”:“用户”,“ _ csrf”:“ f1d88246-28a0-4e64-a988-def4cafa5004”}
我的安全配置是:
http .exceptionHandling().and() .anonymous().and() .servletApi().and() .headers().cacheControl().and() .authorizeRequests() //allow anonymous resource requests .antMatchers("/").permitAll() //allow anonymous POSTs to login .antMatchers(HttpMethod.POST, "/verifyUser").permitAll() .and() .formLogin().loginPage("/signin") .permitAll() .and() .addFilterBefore(new StatelessLoginFilter("/verifyUser", new TokenAuthenticationService("456abc"), new CustomJDBCDaoImpl() , authenticationManager()), UsernamePasswordAuthenticationFilter.class) .addFilterBefore(new StatelessAuthenticationFilter(new TokenAuthenticationService("456abc")), UsernamePasswordAuthenticationFilter.class).httpBasic() .and().csrf().disable().addFilterBefore(new CSRFFilter(), CsrfFilter.class);
编辑#1
我也尝试使用getParameter(“ email”)代替getAttribute(“ email”),但是,整个参数映射在这一点上也是空的。
编辑#2:添加请求内容
Remote Address:127.0.0.1:80Request URL:http://localhost/api/verifyUser/Request Method:POSTStatus Code:502 Bad GatewayResponse Headersview sourceConnection:keep-aliveContent-Length:583Content-Type:text/htmlDate:Sun, 11 Oct 2015 17:23:24 GMTServer:nginx/1.6.2 (Ubuntu)Request Headersview sourceAccept:application/json, text/plain, */*Accept-Encoding:gzip, deflateAccept-Language:en-US,en;q=0.8Connection:keep-aliveContent-Length:81Content-Type:application/x-www-form-urlencodedCookie:XSRF-TOKEN=f1d88246-28a0-4e64-a988-def4cafa5004Host:localhostOrigin:http://localhostReferer:http://localhost/ui/User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36X-XSRF-TOKEN:f1d88246-28a0-4e64-a988-def4cafa5004Form Dataview sourceview URL encoded{"email":"user","password":"user"}:
答案1
小编典典所需的email
和password
数据是参数,而不是属性。ServletRequest中的属性是仅服务器端的数据,您可以在应用程序中使用它们在类之间或JSP之间传递数据。
注意:您必须使用内容类型application/x-www-form-urlencoded
,并确保请求主体的编码格式正确,以便getParameter
在服务器端使用,例如email=user&password=user
。
默认情况下,Angular将对象编码为JSON
转换请求和响应
Angular提供以下默认转换:
请求转换($ httpProvider.defaults.transformRequest和$
http.defaults.transformRequest):如果请求配置对象的data属性包含一个对象,则将其序列化为JSON格式。
Adal angular spring security azure 广告集成
如何解决Adal angular spring security azure 广告集成?
我正在尝试实现 sso 和 spring 安全以与 azure 广告一起工作。使用 Angular 前端和 Spring Boot 后端。这是我的一些代码。我缺少什么帮助? 我收到 403 错误,不知道是什么问题,让 azure 设置了很好的类似示例,但无法在我的应用程序上实现。
componentDidMount(){
populateData(true)
}
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AADAuthenticationFilter aadAuthFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().authorizeRequests()
.antMatchers("/index").permitAll()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll()
.and()
.csrf()
.csrftokenRepository(CookieCsrftokenRepository.withHttpOnlyFalse())
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.deleteCookies("JSESSIONID")
.logoutSuccessUrl("/")
.invalidateHttpSession(true)
.and()
.addFilterBefore(aadAuthFilter,UsernamePasswordAuthenticationFilter.class);
}
}
azure:
activedirectory:
tenant-id: xxxxx-xxxxxx-xxx--xxxxxxxxxx
client-id: xxxxx-xxxxxx-xxx--xxxxxxxxxx
client-secret: xxxxx-xxxxxx-xxx--xxxxxxxxxx
# Optional,default value is http://localhost:8080/
redirect-uri-template: http://localhost:8080/
# groups that you created in your Azure AD tenant
user-group:
allowed-groups: PDP
@CrossOrigin
@RestController
public class LoginController {
@PreAuthorize("hasRole(''PDP'')")
@GetMapping(path = "/hello")
public String hello (@RequestHeader HttpHeaders headers) {
Optional.ofNullable(headers.get(HttpHeaders.AUTHORIZATION)).ifPresent(
h -> System.out.println("AUTHORIZATION HEADER: "+h.get(0))
);
return "{\"value\": \"Hello Word!\"}";
}
@Autowirednsta
private AADAuthenticationProperties aadAuthenticationProperties;
@RequestMapping({"/"})
public ModelAndView index() {
ModelAndView model = new ModelAndView("index");
model.addobject("aad_clientId",aadAuthenticationProperties.getClientId());
model.addobject("aad_tenantId",aadAuthenticationProperties.getTenantId());
model.addobject("aad_redirectUri",Optional
.ofNullable(aadAuthenticationProperties.getRedirectUriTemplate())
.orElse("http://localhost:8080/") );
return model;
}
@PreAuthorize("hasRole(''PDP'')")
@PostMapping(value = SO_URI + SAVE_SO_LIST)
public ResponseEntity<List<SO>> saveSOList(@RequestBody List<SO> soList) {
try {
List<SO> response = soService.saveSOList(soList);
return ResponseEntity.ok(response);
} catch (Exception e) {
throw e;
}
}
}
export function MSALInstanceFactory(): IPublicclientApplication {
return new PublicclientApplication({
auth: {
clientId: ''xxxxx-xxxxxx-xxx--xxxxxxxxxx'',redirectUri: ''http://localhost:4200''
}
});
}
export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
const protectedResourceMap = new Map<string,Array<string>>();
protectedResourceMap.set(''https://graph.microsoft.com/v1.0/me'',[''user.read'',''mail.read'']);
protectedResourceMap.set(''http://localhost:8080/'',[''api://xxxxx-xxxxxx-xxx--xxxxxxxxxx/login'']);
return {
interactionType: InteractionType.Redirect,protectedResourceMap
};
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
Angular 2 http.post不适用于Spring Security
如何解决Angular 2 http.post不适用于Spring Security?
我正在从有角度的前端向春季后端发送凭证。通过http.get
发送凭据时,它可以正常工作。但是当使用http.post
时它不起作用。我在控制器上添加了method = RequestMethod.POST
,不确定为什么它不起作用。在提到问题spring boot starter security post methods not working之后
我添加了csrf().disable()
,但仍然无法正常工作。
春天-
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
Environment env;
@Autowired
UserSecurityService useSecurityService;
private BCryptPasswordEncoder passwordEncoder() {
return SecurityUtility.passwordEncoder();
}
private static final String[] PUBLIC_MATHCES= {
"/css/**","/js/**","/image/**","/book/**","/user/**"
};
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(useSecurityService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(PUBLIC_MATHCES).permitAll()
.anyRequest().authenticated();
http.csrf().disable()
.cors()
.and()
.httpBasic();
}
}
@CrossOrigin(origins = "http://localhost:4200")
@RestController
public class LoginController {
@Autowired
private UserService userService;
@RequestMapping(value = "/token",method = RequestMethod.POST)
public Map<String,String> token(HttpSession session,HttpServletRequest request) {
System.out.println(request.getRemoteHost());
String remoteHost = request.getRemoteHost();
int portNumber = request.getRemotePort();
System.out.println(remoteHost+":"+portNumber);
System.out.println(request.getRemoteAddr());
return Collections.singletonMap("token",session.getId());
}
}
@SpringBootApplication
public class BookStoreApplication implements CommandLineRunner {
@Autowired
UserService userService;
public static void main(String[] args) {
SpringApplication.run(BookStoreApplication.class,args);
}
@Override
public void run(String... args) throws Exception {
User user1=new User();
user1.setUserName("test");
user1.setPassword(SecurityUtility.passwordEncoder().encode("test"));
user1.setEmail("test@test.com");
user1.setEnabled(true);
user1.setFirstName("testFirstName");
user1.setLastName("testLastName");
user1.setPhone("123456789");
Role role1=new Role();
role1.setRoleId((long)1);
role1.setRoleName("ROLE_USER");
UserRole userRole1=new UserRole(user1,role1);
Set<UserRole> userRoles1=new HashSet<UserRole>();
userRoles1.add(userRole1);
userService.createuser(user1,userRoles1);
User user2=new User();
user2.setUserName("admin");
user2.setPassword(SecurityUtility.passwordEncoder().encode("admin"));
user2.setEmail("admin@admin.com");
user2.setEnabled(true);
user2.setFirstName("adminFirstName");
user2.setLastName("adminLastName");
user2.setPhone("223456789");
Role role2=new Role();
role2.setRoleId((long) 2);
role2.setRoleName("ROLE_ADMIN");
UserRole userRole2=new UserRole(user2,role2);
Set<UserRole> userRoles2=new HashSet<UserRole>();
userRoles2.add(userRole2);
userService.createuser(user2,userRoles2);
}
}
角度-
import { Injectable } from ''@angular/core'';
import {Http,Headers } from ''@angular/http'';
import { Observable } from ''rxjs/Observable'';
@Injectable()
export class LoginService {
constructor(private http:Http) { }
sendCredentials(username:String,password:String){
let url="http://localhost:8181/token";
let encodedCred=btoa(username+":"+password);
let basicHeader="Basic "+encodedCred;
let header=new Headers({
"Content-Type": "application/json","Authorization": basicHeader
});
return this.http.post(url,{headers:header});
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
Angular 2,Spring boot,spring security,登录表单
我有一个在http:// localhost:4200上运行的前端应用程序,角度为2(我使用了angular-cli来生成项目).
应用程序运行没有任何问题(我可以使用Angular 2 Http服务从/向数据库获取和发布信息:
getList () {
return this._http.get("http:// localhost:8080/").map(res => res.json());
}
另一方面,我有一个在http:// localhost:8080 /(注意端口)上使用spring boot运行的后端应用程序,它为我的angular 2应用程序提供REST Api.
从http:// localhost:4200 /发送到http:// localhost:8080 /的请求按预期工作.
在我使用spring framework& ;;编写应用程序之前angularJS 1,spring security在同一个app(maven项目)中负责登录和安全.
现在我有两个独立的应用程序通过http进行通信(RESTful Api与弹簧启动,前端Api与角度2)
如何设置我的登录表单以及放置它的位置,以及如何使用angular 2应用程序配置弹簧安全性?
你有几个选择.
>登录可以在NodeJS服务器上处理,然后可以调用
Spring Boot应用程序进行身份验证和授权.(我想,你可能需要做一些调整,比如使用快速服务器而不是精简服务器.看看这里https://stackoverflow.com/a/37561973/6785908)
>初始开发后,您可以复制AngularJS
Spring MVC(Spring Boot)服务器的资源并使用它来提供服务
您的页面(以及其他API),就像您正在做的那样
之前.
>让Angular App调用spring boot Service(我想,你
正在使用$http.post提交表单,如果是这样的话
可以只更改URL,以便它可以命中弹簧启动应用程序.)
对于生产部署,使用Nginx / httpd来提供静态
文件(AngularJS / CSS等)和路由/代理所有的动态请求
春季启动应用程序.
我强烈建议第3种选择.
Angular.Js + Spring Security 的权限控制使用
一. 引言
在系统中,常常因为用户的角色不同,拥有不同的功能,那么涉及到一个问题,就是UI界面如何根据用户角色的不太显示不同的UI界面,后台如何避免没有权限的用户进行api 接口的访问。
二. Angular.JS 权限的指令
Angular.Js中指令分为属性型指令和结构型指令。
1.指令得基本使用方法
angular 创建指令的命令:
ng generate directive [directive-name]
属性型指令:主要用于操作元素的属性和样式。angular中提供的内置结构型指令有ngStyle、ngClass等。
eg:
<div [ngClass]="{''red-background'': isRed}">这是V层的使用</div>
在angular的c层中,根据isRed 属性的值true 还是 false 来决定V层是否添加该样式。
结构型指令:主要用于改变DOM的结构和布局。angular中提供的内置结构型指令有ngIf、ngFor、ngSwitch等。 在V层使用的时候,需要在指令名前加前缀 , 这是angular的语法糖,编译器会将起转换为[] 包裹的属性型形式。
eg:
<div *ngIf="condition">V层使用结构型指令ngIf</div>
编译器看见前缀* 后,将起转换为:
<ng-template [ngIf]="condition">
<div>这是编译器转换后的形式</div>
</ng-template>
在angular的c层中,根据condition属性的值true 还是 false 来决定V层是否改变DOM的结构和布局。
若您还需了解更多指令selector的设置,可移步到Angular 指令注解的属性解释
2.用angular结构型指令实现前台权限的控制。
需求:不同用户登录系统,展示不同的菜单,或添加,编辑,删除等操作按钮。
思路:
1 创建权限指令
2 在指令中获取当前登录用户
3 在指令中做逻辑判断,用户拥有权限 创建嵌入视图, 用户没有权限 什么都不做或清除嵌入的视图
4 在v层中元素中,使用该指令
具体实现:
V成使用:
<div *appBePermit="[''admin'']">holle</div>
指令:
@Directive({
selector: ''[appBePermit]''
})
export class BePermitDirective implements OnInit{
// 模拟一个当前登录用户
user = {name: ''张三'', password: ''123456'', authorities: [''admin'', ''user'']} as User;
// 接收属性值
@Input(''appBePermit'') authorities: string[] | undefined | string;
constructor(private viewContainer: ViewContainerRef,
private readonly templateRef: TemplateRef<any>,) {
}
ngOnInit() {
console.log(this.authorities)
// 获取当前用户
const currentUser = this.user;
// 逻辑判断
const hasView = this.viewContainer.length;
if (hasView === 0 && currentUser.authorities.some(item => this.authorities?.includes(item))) {
// 有权限 创建陷入视图
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
// 清除容器的视图
this.viewContainer.clear();
}
}
}
interface User {
name: string,
password: string,
authorities: string[]
}
其中:TemplateRef用于表示内嵌的<ng-template>模板元素。
二. 基于Spring Security 的授权使用
spring Security 是一个框架,提供 认证(authentication)、授权(authorization) 和 保护,以抵御常见的攻击。
在 Spring Security 中,与认证、授权相关的校验其实都是利用一系列的过滤器来完成的,这些过滤器共同组成了一个过滤器链。
1 项目启用spring security
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
在配置类中,添加注解使其生效
@EnableWebSecurity (启用Spring Security的Web安全配置)
@EnableGlobalMethodSecurity(prePostEnabled = true) (启用Spring Security的@PreAuthorize、@PostAuthorize、@PreFilter和@PostFilter注解)
继承WebSecurityConfigurerAdapter适配器类,自定义安全策略
eg:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.and().cors()
.and().csrf().disable();
}
}
执行以上的操作后,Sping Security 就可以在系统中使用了。
在每个方法前面,注解使用@PreAuthorize("hasAnyAuthority(''access'', ''ROLE_ADMIN'')")可控制拥有access, ROLE_ADMIN中任意一个权限即可访问该方法。
用户角色的存储
总结
Spring Security 未使用过,仅仅处于看到过的阶段,需要写Demo 进行学习一下,当前学习的都很浅,还需要深入学习一下,画图理解一下其原理。
关于Spring Security吃AngularJS POST请求和spring security postman的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于Adal angular spring security azure 广告集成、Angular 2 http.post不适用于Spring Security、Angular 2,Spring boot,spring security,登录表单、Angular.Js + Spring Security 的权限控制使用的相关信息,请在本站寻找。
本文标签: