Angular前端与Spring后端安全通信。
创始人
2024-10-29 02:30:20
0

Angular前端与Spring后端之间的安全通信可以使用以下解决方案:

  1. 使用Token-Based身份验证:
    • 前端登录后,后端返回一个包含访问令牌的JWT(JSON Web Token)。
    • 前端在每个后续请求的请求头中添加该令牌。
    • 后端验证令牌的有效性并处理请求。

在Angular前端中,可以使用Angular的HttpClient模块来发送请求。以下是一个示例代码:

import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class ApiService {
  private apiUrl = 'http://localhost:8080/api';
  private headers = new HttpHeaders({ 'Content-Type': 'application/json' });

  constructor(private http: HttpClient) {}

  login(username: string, password: string): Observable {
    const body = { username: username, password: password };
    return this.http.post(`${this.apiUrl}/login`, body, { headers: this.headers });
  }

  getData(): Observable {
    const token = localStorage.getItem('token'); // 从localStorage中获取保存的令牌
    const headers = this.headers.append('Authorization', `Bearer ${token}`);
    return this.http.get(`${this.apiUrl}/data`, { headers: headers });
  }
}

在Spring后端中,可以使用Spring Security来处理身份验证和授权。以下是一个示例代码:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Autowired
    private UserDetailsService userDetailsService;
    
    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() {
        return new JwtAuthenticationFilter();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
            .authorizeRequests()
            .antMatchers("/api/login").permitAll()
            .anyRequest().authenticated()
            .and()
            .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    
    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        
        if (user == null) {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }

        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
            new ArrayList<>());
    }
}
@RestController
@RequestMapping("/api")
public class ApiController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @PostMapping("/login")
    public ResponseEntity authenticateUser(@RequestBody LoginRequest loginRequest) {
        Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));

        SecurityContextHolder.getContext().setAuthentication(authentication);
        String jwt = jwtTokenProvider.generateToken(authentication);
        return ResponseEntity.ok(new JwtAuthenticationResponse(jwt));
    }

    @GetMapping("/data")
    public ResponseEntity getData() {
        // 处理请求,返回数据
        return ResponseEntity.ok("Some data");
    }
}

以上是一个简单的示例代码,实现了基于Token的身份验证和安全通信。在实际应用中,可能还需要添加更多的安全措施,例如对角色和权限的控制,以及HTTPS的使用来保护通信。

相关内容

热门资讯

五分钟绝活!潮友会鱼虾蟹怎么发... 五分钟绝活!潮友会鱼虾蟹怎么发现软件控制,四川家园游戏辅助,教你攻略(有挂解密)-哔哩哔哩1、操作简...
第九分钟策略!广西友乐app辅... 第九分钟策略!广西友乐app辅助工具,湖北卡五星技能,普及教程(有挂讲解)-哔哩哔哩1、全新机制【广...
4分钟要领!八闽掌上辅助软件,... 4分钟要领!八闽掌上辅助软件,对战互娱有辅助吗,揭秘攻略(有挂方针)-哔哩哔哩1、完成八闽掌上辅助软...
3分钟机巧!财神十三章辅助软件... 3分钟机巧!财神十三章辅助软件,指尖捕鱼bgm,可靠教程(有挂助手)-哔哩哔哩;1、财神十三章辅助软...
七分钟模块!胡易决胜麻架辅助,... 七分钟模块!胡易决胜麻架辅助,情怀宜春辅助挂定制交易平台,玩家教你(有挂秘籍)-哔哩哔哩1、玩家可以...
3分钟烘培!牵手辅助神器下载,... 3分钟烘培!牵手辅助神器下载,新海贝之城app破解,教你教程(有挂总结)-哔哩哔哩新海贝之城app破...
第七分钟课程!悠闲游戏辅助,牛... 第七分钟课程!悠闲游戏辅助,牛总管手游辅助,爆料教程(有挂存在)-哔哩哔哩亲,关键说明,牛总管手游辅...
3分钟演示!麻雀智能辅助软件,... 3分钟演示!麻雀智能辅助软件,传送屋激k有挂吗,力荐教程(今日头条)-哔哩哔哩1、每一步都需要思考,...
第8分钟经验!好友赣南辅助是真... 第8分钟经验!好友赣南辅助是真的吗,蛮王大厅辅助教程,分享教程(有挂教学)-哔哩哔哩1、起透看视 好...
九分钟法门!中至赣牌圈五十k黑... 九分钟法门!中至赣牌圈五十k黑科技,开心泉州小程序有挂吗,力荐教程(有挂解密)-哔哩哔哩小薇(透视辅...