<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Jhone </title>
    <description>The latest articles on DEV Community by Jhone  (@wnjsjen).</description>
    <link>https://dev.to/wnjsjen</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3040605%2Feb8b015f-86bc-483e-9083-c82cddaa3517.png</url>
      <title>DEV Community: Jhone </title>
      <link>https://dev.to/wnjsjen</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/wnjsjen"/>
    <language>en</language>
    <item>
      <title>Frontend</title>
      <dc:creator>Jhone </dc:creator>
      <pubDate>Thu, 24 Apr 2025 12:15:21 +0000</pubDate>
      <link>https://dev.to/wnjsjen/frontend-549c</link>
      <guid>https://dev.to/wnjsjen/frontend-549c</guid>
      <description>&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, {
  createContext,
  useContext,
  useEffect,
  useMemo,
  useState,
} from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  setIsLogin,
  setLoginUserDetails,
} from "../../src/components/common/redux/action.jsx";

import axios from "axios";
import { Roles } from "../components/utils/roles.js";
const AuthContext = createContext();

export const AuthProvider = ({ children }) =&amp;gt; {
    const dispatch = useDispatch()
    const loginUserDetails = useSelector((state) =&amp;gt; state?.token?.Auth?.loginUserDetails)

    const [ekamMenu, setEkamMenu] = useState([]);
    const contextValue = useMemo(() =&amp;gt; ({
        ekamMenu,
        setEkamMenu,
        loginUserDetails,
      }), [ekamMenu, setEkamMenu, loginUserDetails]);

const fetchUser = async () =&amp;gt; {
    const urlParams = new URLSearchParams(window.location.search);
    const randomString = urlParams.get('token');
    const myHeaders = new Headers();
    myHeaders.append("Cookie", "Path=/ekam");
    myHeaders.append("Content-Type", "application/json");

    const requestOptions = {
        method: "GET",
        headers: myHeaders,
        redirect: "follow"
    };

    try {
        if (randomString) {
            const isValidResponse = await fetch(`${import.meta.env.VITE_LOGIN}/validateToken/${randomString}`, requestOptions);
            const isValid = await isValidResponse.text();
            console.log(isValid);


            if (isValid) {
                try {
                    const responseTokenResponse = await fetch(`${import.meta.env.VITE_LOGIN}/token/${randomString}`, requestOptions);
                    const responseToken = await responseTokenResponse.text();
                    console.log(responseToken);


                    const responseUserResponse = await fetch(`${import.meta.env.VITE_RBAC}/extractDetails?token=${responseToken}`, requestOptions);
                    const responseUser = await responseUserResponse.json();
                    console.log(responseUser);
                    await fetch(`${import.meta.env.VITE_LOGIN}/removeToken/${randomString}`, { method: 'DELETE', headers: myHeaders });

                    console.log("USER", responseUser)

                    const registrationOptions = {
                        method: "POST",
                        headers: myHeaders,
                        body: JSON.stringify({ username: responseUser?.email, password: responseUser?.email + "Testing@1234567" })
                    };
                    console.log("USER 2", responseUser)
                    const irsRegistrationResponse = await fetch(import.meta.env.VITE_USER_REGISTER_JWT_TOKEN, registrationOptions);
                    const irsRegistrationData = await irsRegistrationResponse.text();
                    console.log(irsRegistrationData,"Registration data");

                    if (irsRegistrationData == "User Already Exists!" || irsRegistrationData == "User Registered Successfully!") {
                       console.log("into if statement");

                        const loginOptions = {
                            method: "POST",
                            headers: myHeaders,
                            body: JSON.stringify({ username: responseUser?.email, password: responseUser?.email + "Testing@1234567" })
                        };

                        const irsTokenResponse = await fetch(import.meta.env.VITE_JWT_TOKEN, loginOptions);
                        const irsTokenData = await irsTokenResponse.json();

                        console.log(irsTokenData,"is token data");

                        dispatch(setIsLogin(true));
                        console.log("here");
                        console.log("this is jwt token");
                        console.log(irsTokenData.jwtToken);
                        responseUser.jwtToken = irsTokenData?.jwtToken;
                        console.log("this is response with jwtToken");

                        console.log(responseUser);
                        dispatch(setLoginUserDetails(responseUser));
                        const baseUrl = window.location.origin + window.location.pathname;
                        window.history.replaceState({}, document.title, baseUrl);
                    }
                } catch (err) {
                    console.error(err);
                }
            }
        } else {

            console.log("into esle");

            const irsRegistrationResponse = await axios.post(import.meta.env.VITE_USER_REGISTER_JWT_TOKEN, { username:"priyanka.rodda@gmail.com", password: "Testing@1234567" })
            if (irsRegistrationResponse?.data === "User Already Exists!" || irsRegistrationResponse?.data === "User Register Successfully!") {
            const irsTokenResponse = await axios.post(import.meta.env.VITE_JWT_TOKEN, { username: "priyanka.rodda@gmail.com", password: "Testing@1234567" })
            dispatch(setIsLogin(true))
            dispatch(setLoginUserDetails(
                {
                "bankName": null,
                "userType": "NPCI",
                "userName": "vivek.upadhyay",
                "email": "priyanka.rodda@npci.org.in",
                "department":"Information Security",
                "projectOwner":"test",
                "selectedSite": [
                    {
                        "site": "PCOM",
                        "role": Roles.USER_HOD,
                        "menus": [
                          {  menuName: "Dashboard"},
                          {  menuName: "Inventory"},
                          {  menuName:  "Tracking"},
                          {  menuName: "AgentMaster"},
                          {  menuName: "AgentEnvMap"},
                          {  menuName: "AllowedPorts"},

                        ]
                        }
                    ],


                }
             ))
            }


        }
    } catch (err) {
        console.log("into catch");
        console.error(err);
    }
};

    useEffect(() =&amp;gt; {
        fetchUser();
    }, [])

    return (

        &amp;lt;AuthContext.Provider value={contextValue}&amp;gt;
        {children}
      &amp;lt;/AuthContext.Provider&amp;gt;
    )
}

export const useAuth = () =&amp;gt; {
    const context = useContext(AuthContext);
    if (!context) {
        throw new Error("You are unthorized for this page")
    }
    return context;
}

export default AuthContext;



need to resolved 

"Improper Session handling

The application allows a user to re-access a session after logout by simply pasting a previously copied URL. This indicates that: The session token (likely stored in a cookie or as a URL parameter) remains valid even after logout. Session termination is incomplete or ineffective, allowing the session to be reused. The app might not be invalidating or expiring the session server-side when a user logs out."    "Session Hijacking Risk:
Anyone with access to the URL or session token can regain access to the user’s account after logout.

Bypassing Logout Mechanism:
The logout process gives a false sense of security—users think they’ve logged out, but their session can still be reused.

Unauthorized Access:On shared or public machines, someone could easily revisit a copied link and gain unauthorized access to sensitive data."   "Proper Session Invalidation

Ensure that on logout:
The session token is deleted from the client (e.g., cookie cleared).
The session is invalidated server-side (e.g., token or session ID marked as expired or removed from the database/store).

Token Rotation:
Use short-lived access tokens and refresh tokens with strict validation. Tokens should become unusable immediately after logout.

Avoid Session Tokens in URLs:
Never pass session tokens in URLs (GET parameters). URLs can be cached, logged, or easily shared.

Implement Expiry and Inactivity Timeouts:
Set a reasonable expiry time and inactivity timeout on sessions to limit exposure.

Use Secure Cookies with Flags:
Store session tokens in cookies with the following flags:
HttpOnly: Prevents access from JavaScript.
Secure: Ensures it's sent only over HTTPS.
SameSite: Protects against CSRF."
"Back &amp;amp; Refresh Attack

During the assessment it was observed that the session does not get terminated at the server after clicking logout button"  An attacker can use previous used or available session to access the application and impersonate valid user to carry out malicious activity or steel any user information.  The user’s HTTP session should be terminated on the server immediately after a logout action is performed. It is important to note that simply deleting the cookie from the browser will not terminate the server session. The session must be invalidated at the server, using the HTTP container’s intrinsic session abandonment mechanism.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>secru</title>
      <dc:creator>Jhone </dc:creator>
      <pubDate>Thu, 24 Apr 2025 06:57:00 +0000</pubDate>
      <link>https://dev.to/wnjsjen/secru-a2f</link>
      <guid>https://dev.to/wnjsjen/secru-a2f</guid>
      <description>&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.infra_automation.config;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.header.writers.StaticHeadersWriter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@EnableWebSecurity
@Configuration
public class SecurityConfig {

    private final String authApiBaseURL;
    private final String registrationURL;
    private final String loginURL;

    @Autowired
    public SecurityConfig(
            @Value("${api.auth.registration.url}") String registrationURL,
            @Value("${api.auth.base.url}") String authApiBaseUrl,
            @Value("${api.auth.login.url}") String loginURL,
            @Value("${auth.allow.origin}") String allowOriginUrl,
            @Value("#{'${auth.allow.method}'.split(',')}") List&amp;lt;String&amp;gt; allowMethods
    ) {
        this.registrationURL = registrationURL;
        this.loginURL = loginURL;
        this.authApiBaseURL = authApiBaseUrl;
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(List.of("https://ekam.npci.org.in", "http://localhost:3003"));
        configuration.setAllowedMethods(List.of("GET", "POST", "DELETE", "PUT"));
        configuration.setAllowedHeaders(List.of("*"));
        configuration.setAllowCredentials(false);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(
            HttpSecurity httpSecurity,
            JwtAuthenticationFilter jwtAuthenticationFilter,
            JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint
    ) throws Exception {

        httpSecurity
                .csrf(AbstractHttpConfigurer::disable)
                .cors(Customizer.withDefaults())
                .authorizeHttpRequests(auth -&amp;gt; auth
                        .requestMatchers(
                                authApiBaseURL + registrationURL + "/**",
                                authApiBaseURL + loginURL + "/**",
                                "/InfraBk/api/v1/inventory/flushDb",
                                "/InfraBk/api/v1/inventory/upload-inventory",
                                "InfraBk/api/v1/users/getProjectByName/**",
                                "InfraBk/api/v1/trackings/**"

                        ).permitAll()
                        .anyRequest().authenticated())
                .exceptionHandling(exception -&amp;gt;
                        exception.authenticationEntryPoint(jwtAuthenticationEntryPoint))
                .sessionManagement(session -&amp;gt;
                        session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .headers(headers -&amp;gt; headers
                        .defaultsDisabled()
                        .addHeaderWriter(new StaticHeadersWriter("Expect-CT", "max-age=3600, enforce"))
                        .addHeaderWriter(new StaticHeadersWriter("Referrer-Policy", "strict-origin-when-cross-origin"))
                        .addHeaderWriter(new StaticHeadersWriter("Permissions-Policy", "geolocation=(), microphone=(), camera=(), interest-cohort=()"))
                        .addHeaderWriter(new StaticHeadersWriter("Strict-Transport-Security", "max-age=31536000 ; includeSubDomains"))
                        .addHeaderWriter(new StaticHeadersWriter("X-Frame-Options", "DENY"))
                        .addHeaderWriter(new StaticHeadersWriter("X-Content-Type-Options", "nosniff"))
                        .addHeaderWriter(new StaticHeadersWriter("X-XSS-Protection", "1; mode=block"))
                        .addHeaderWriter(new StaticHeadersWriter("Expect-CT", "max-age=3600, enforce"))
                        .addHeaderWriter(new StaticHeadersWriter("Referrer-Policy", "strict-origin-when-cross-origin"))
                        .addHeaderWriter(new StaticHeadersWriter("Permissions-Policy", "geolocation=(), microphone=(), camera=(), interest-cohort=()"))
                        .addHeaderWriter((request, response) -&amp;gt; response.setHeader("Content-Security-Policy",
                                "default-src 'self'; " +
                                        "script-src 'self'; " +
                                        "frame-ancestors 'self'; " +
                                        "img-src 'self'; " +
                                        "style-src 'self'; " +
                                        "object-src 'none'; " +
                                        "frame-src 'self'; " +
                                        "form-action 'self'; " +
                                        "media-src 'self';"
                        ))
                )
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        return httpSecurity.build();
    }

    @Bean
    public InMemoryUserDetailsManager userDetailsManager() {
        return new InMemoryUserDetailsManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
            throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Tesdfghjkl;'</title>
      <dc:creator>Jhone </dc:creator>
      <pubDate>Thu, 24 Apr 2025 04:49:22 +0000</pubDate>
      <link>https://dev.to/wnjsjen/tesdfghjkl-56po</link>
      <guid>https://dev.to/wnjsjen/tesdfghjkl-56po</guid>
      <description>&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ResponseEntity&amp;lt;ApiResponse&amp;lt;Object&amp;gt;&amp;gt; updateStageAndStatus(@PathVariable Long requestId, @Valid @RequestBody StageUpdateDTO stageUpdate) {
        try {
            // Decrypt the payload 
            System.out.println("stageUpdate :: ::"+ stageUpdate);

            String decryptedData = CryptoUtil.decrypt(String.valueOf(stageUpdate)).toString();

            System.out.println("decryptedData"+decryptedData);

            // Check if the stageName is a number (index) and map it to the stage name
            String stageName = stageUpdate.getStageName();
            if (stageName != null &amp;amp;&amp;amp; stageName.matches("\\d+")) {
                int stageIndex = Integer.parseInt(stageName);
                if (stageIndex &amp;lt; 0 || stageIndex &amp;gt;= StageOrder.getStageOrder().size()) {
                    throw new IllegalArgumentException("Invalid stage index: " + stageIndex);
                }
                // Map the index to the corresponding stage name
                stageUpdate.setStageName(StageOrder.getStageOrder().get(stageIndex));
            }
            // Validate stage order and process stage update in the service layer
            TrackingRequestDto updatedTracking = service.updateStageAndStatus(requestId, stageUpdate, StageOrder.getStageOrder());
            // Return success response
            return ResponseEntity.ok(ResponseUtil.success(updatedTracking, "Stage updated successfully"));
        } catch (IllegalArgumentException e) {
            // Return bad request with error response
            return ResponseEntity.badRequest().body(ResponseUtil.error(e.getMessage()));
        } catch (Exception e) {
            // Return internal server error with error response
            return ResponseEntity.internalServerError().body(ResponseUtil.error("Error updating stage: " + e.getMessage()));
        }
    }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**
     * Decrypts the given encrypted data and converts it back to the specified type.
     *
     * @param encryptedData the Base64 encoded encrypted string
     * @param valueType the expected type to convert the decrypted JSON back into
     * @param &amp;lt;T&amp;gt; the type parameter
     * @return the decrypted object of type T
     * @throws Exception if decryption fails
     */
    public static &amp;lt;T&amp;gt; T decrypt(String encryptedData, Class&amp;lt;T&amp;gt; valueType) throws Exception {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);
            String decryptedJson = new String(decryptedBytes, StandardCharsets.UTF_8);
            return objectMapper.readValue(decryptedJson, valueType);
        } catch (Exception e) {
            // Log error as needed
            throw new Exception("Decryption failed", e);
        }
    }

    /**
     * Decrypts the given encrypted data and returns it as a generic Object.
     *
     * @param encryptedData the Base64 encoded encrypted string
     * @return the decrypted object (typically a Map or List, depending on the JSON)
     * @throws Exception if decryption fails
     */
    public static Object decrypt(String encryptedData) throws Exception {
        return decrypt(encryptedData, Object.class);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.infra_automation.dto;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * Data Transfer Object for updating a stage.
 */
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class StageUpdateDTO {


    @NotBlank(message = "Hostname preference is required")
    @Size(max = 255, message = "Hostname preference must be 255 characters or less")
    @Pattern(regexp = "^[a-zA-Z0-9 ]*$", message = "HTML or script tags are not allowed")
    private String stageName;  // e.g., "HOD_Approval"


    @NotBlank(message = "Status is required")
    @Pattern(regexp = "^(completed|pending|rejected)$", message = "Invalid status not in this format completed|pending|rejected")
    @Pattern(regexp = "^[a-zA-Z0-9 ]*$", message = "HTML or script tags are not allowed")
    private String status;     // e.g., "Completed"


    @Pattern(regexp = "^[a-zA-Z0-9 ]*$", message = "HTML or script tags are not allowed")
    @Size(max = 100, message = "Done by must be 100 characters or less")
    private String doneBy;



    @Size(max = 255, message = "Remarks must be 255 characters or less")
    @Pattern(regexp = "^[a-zA-Z0-9 ]*$", message = "HTML or script tags are not allowed")
    private String remarks;    // e.g., "VM request raised by Admin"


    @Pattern(regexp = "^[a-zA-Z0-9 ]*$", message = "HTML or script tags are not allowed")
    private String action;

    @Size(max = 100, message = "Title must be 100 characters or less")
    @Pattern(regexp = "^[a-zA-Z0-9 ]*$", message = "HTML or script tags are not allowed")
    private String title;      // e.g., "Hod Approval"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>zxsdfghjk,</title>
      <dc:creator>Jhone </dc:creator>
      <pubDate>Fri, 11 Apr 2025 08:51:33 +0000</pubDate>
      <link>https://dev.to/wnjsjen/zxsdfghjk-278g</link>
      <guid>https://dev.to/wnjsjen/zxsdfghjk-278g</guid>
      <description>&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Configuration
@EnableWebSecurity
public class SecurityConfig {
 private final JwtUtil jwtUtil;
 private CorsConfigurationSource corsConfigurationSource;
 public SecurityConfig(JwtUtil jwtUtil, CorsConfigurationSource corsConfigurationSource) {
  this.jwtUtil = jwtUtil;
  this.corsConfigurationSource = corsConfigurationSource;
 }

 @Bean
 public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
     http.csrf(csrf -&amp;gt; csrf.disable())
         .cors(Customizer.withDefaults())
         .authorizeHttpRequests(authz -&amp;gt; authz
                 .requestMatchers("/v1/auth/**", "/v1/card-bin-mapping/getByBin",
                         "/v1/card-bin-mapping/uploadCardBinMapping", "/swagger-ui.html", "/swagger-ui/**",
                         "/api-docs/**", "/swagger-resources/**", "/webjars/**")
                 .permitAll().anyRequest().authenticated())
         .headers(headers -&amp;gt; headers
                 .defaultsDisabled()
                 .addHeaderWriter(new StaticHeadersWriter("Content-Security-Policy", "default-src 'self';"))
                 .addHeaderWriter(new StaticHeadersWriter("Expect-CT", "max-age=3600, enforce"))
                 .httpStrictTransportSecurity(
                     hsts -&amp;gt; hsts.includeSubDomains(true).maxAgeInSeconds(31536000).preload(true))
                 .addHeaderWriter(new StaticHeadersWriter("Referrer-Policy", "strict-origin-when-cross-origin"))
                 .addHeaderWriter(new StaticHeadersWriter("Permissions-Policy",
                     "geolocation=(), microphone=(), camera=(), interest-cohort=()")))
         .sessionManagement(session -&amp;gt; session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
         .addFilterBefore(new HiddenRequestFilter(), UsernamePasswordAuthenticationFilter.class)
         .addFilterBefore(new JwtAuthenticationFilter(jwtUtil), UsernamePasswordAuthenticationFilter.class);
     return http.build();
 } 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>sdfghjk</title>
      <dc:creator>Jhone </dc:creator>
      <pubDate>Fri, 11 Apr 2025 08:50:09 +0000</pubDate>
      <link>https://dev.to/wnjsjen/sdfghjk-13j4</link>
      <guid>https://dev.to/wnjsjen/sdfghjk-13j4</guid>
      <description>&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Configuration
@EnableWebSecurity
public class SecurityConfig {
 private final JwtUtil jwtUtil;
 private CorsConfigurationSource corsConfigurationSource;
 public SecurityConfig(JwtUtil jwtUtil, CorsConfigurationSource corsConfigurationSource) {
  this.jwtUtil = jwtUtil;
  this.corsConfigurationSource = corsConfigurationSource;
 }

 @Bean
 public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
     http.csrf(csrf -&amp;gt; csrf.disable())
         .cors(Customizer.withDefaults())
         .authorizeHttpRequests(authz -&amp;gt; authz
                 .requestMatchers("/v1/auth/**", "/v1/card-bin-mapping/getByBin",
                         "/v1/card-bin-mapping/uploadCardBinMapping", "/swagger-ui.html", "/swagger-ui/**",
                         "/api-docs/**", "/swagger-resources/**", "/webjars/**")
                 .permitAll().anyRequest().authenticated())
         .headers(headers -&amp;gt; headers
                 .defaultsDisabled()
                 .addHeaderWriter(new StaticHeadersWriter("Content-Security-Policy", "default-src 'self';"))
                 .addHeaderWriter(new StaticHeadersWriter("Expect-CT", "max-age=3600, enforce"))
                 .httpStrictTransportSecurity(
                     hsts -&amp;gt; hsts.includeSubDomains(true).maxAgeInSeconds(31536000).preload(true))
                 .addHeaderWriter(new StaticHeadersWriter("Referrer-Policy", "strict-origin-when-cross-origin"))
                 .addHeaderWriter(new StaticHeadersWriter("Permissions-Policy",
                     "geolocation=(), microphone=(), camera=(), interest-cohort=()")))
         .sessionManagement(session -&amp;gt; session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
         .addFilterBefore(new HiddenRequestFilter(), UsernamePasswordAuthenticationFilter.class)
         .addFilterBefore(new JwtAuthenticationFilter(jwtUtil), UsernamePasswordAuthenticationFilter.class);
     return http.build();
 } 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Hhhh</title>
      <dc:creator>Jhone </dc:creator>
      <pubDate>Fri, 11 Apr 2025 07:44:30 +0000</pubDate>
      <link>https://dev.to/wnjsjen/hhhh-1l1i</link>
      <guid>https://dev.to/wnjsjen/hhhh-1l1i</guid>
      <description>&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.infra_automation.config;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@EnableWebSecurity
@Configuration
public class SecurityConfig {

    private final String authApiBaseURL;
    private final String registrationURL;
    private final String loginURL;
    private final String allowOriginUrl;
    private final List&amp;lt;String&amp;gt; allowMethods;

    @Autowired
    public SecurityConfig(
            @Value("${api.auth.registration.url}") String registrationURL,
            @Value("${api.auth.base.url}") String authApiBaseUrl,
            @Value("${api.auth.login.url}") String loginURL,
            @Value("${auth.allow.origin}") String allowOriginUrl,
            @Value("#{'${auth.allow.method}'.split(',')}") List&amp;lt;String&amp;gt; allowMethods
    ) {
        this.registrationURL = registrationURL;
        this.loginURL = loginURL;
        this.authApiBaseURL = authApiBaseUrl;
        this.allowOriginUrl = allowOriginUrl;
        this.allowMethods = allowMethods;
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(List.of("https://ekam.npci.org.in", "http://localhost:3003"));
        configuration.setAllowedMethods(List.of("GET", "POST", "DELETE", "PUT"));
        configuration.setAllowedHeaders(List.of("*"));
        configuration.setAllowCredentials(false); // Set to false as requested

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(
            HttpSecurity httpSecurity,
            JwtAuthenticationFilter jwtAuthenticationFilter,
            JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint
    ) throws Exception {

        httpSecurity
                .headers(headers -&amp;gt; headers
                        .addHeaderWriter((request, response) -&amp;gt;
                                response.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload"))
                        .addHeaderWriter((request, response) -&amp;gt;
                                response.setHeader("Content-Security-Policy",
                                        "default-src 'self'; " +
                                                "script-src 'self'; " +
                                                "style-src 'self'; " +
                                                "frame-ancestors 'self'; " +
                                                "img-src 'self'; " +
                                                "object-src 'none'; " +
                                                "frame-src 'self'; " +
                                                "form-action 'self'; " +
                                                "media-src 'self';"))
                        .addHeaderWriter((request, response) -&amp;gt;
                                response.setHeader("Expect-CT", "max-age=3600, enforce"))
                        .addHeaderWriter((request, response) -&amp;gt;
                                response.setHeader("X-XSS-Protection", "1; mode=block"))
                        .addHeaderWriter((request, response) -&amp;gt;
                                response.setHeader("X-Content-Type-Options", "nosniff"))
                        .referrerPolicy(referrer -&amp;gt;
                                referrer.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.SAME_ORIGIN))
                )
                .cors(Customizer.withDefaults())
                .csrf(csrf -&amp;gt; csrf.disable())
                .authorizeHttpRequests(auth -&amp;gt; auth
                        .requestMatchers(
                                authApiBaseURL + registrationURL + "/**",
                                authApiBaseURL + loginURL + "/**",
                                "/InfraBk/api/v1/inventory/flushDb",
                                "/InfraBk/api/v1/inventory/upload-inventory"
                        ).permitAll()
                        .anyRequest().authenticated()
                )
                .exceptionHandling(exception -&amp;gt;
                        exception.authenticationEntryPoint(jwtAuthenticationEntryPoint))
                .sessionManagement(session -&amp;gt;
                        session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        return httpSecurity.build();
    }

    @Bean
    public InMemoryUserDetailsManager userDetailsManager() {
        return new InMemoryUserDetailsManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
            throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>asdfg</title>
      <dc:creator>Jhone </dc:creator>
      <pubDate>Fri, 11 Apr 2025 07:39:19 +0000</pubDate>
      <link>https://dev.to/wnjsjen/asdfg-3npc</link>
      <guid>https://dev.to/wnjsjen/asdfg-3npc</guid>
      <description>&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.infra_automation.config;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.security.authentication.AuthenticationManager;

import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;

import org.springframework.security.config.http.SessionCreationPolicy;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import org.springframework.security.crypto.password.PasswordEncoder;

import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import org.springframework.security.web.SecurityFilterChain;

import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;
import org.springframework.web.cors.CorsConfiguration;

import org.springframework.web.cors.CorsConfigurationSource;

import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@EnableWebSecurity

@Configuration

public class SecurityConfig  {

//    @Value("${api.auth.registration.url}")

//    private String registrationURL;

//

//    @Value("${api.auth.login.url}")

//    private String loginURL;

//

//    @Value("${api.allowed.origin}")

//    private String allowedOrigin;


    private final String authApiBaseURL;

    private final String registrationURL;

    private final String loginURL;

    private final String allowOriginUrl;


    private final List&amp;lt;String&amp;gt; allowMethods;


    @Autowired

    public SecurityConfig(

            @Value("${api.auth.registration.url}") String registrationURL,

            @Value("${api.auth.base.url}") String authApiBaseUrl,

            @Value("${api.auth.login.url}") String loginURL,

            @Value("${auth.allow.origin}") String allowOriginUrl,

            @Value("#{'${auth.allow.method}'.split(',')}") List&amp;lt;String&amp;gt; allowMethods


    ) {

        this.registrationURL = registrationURL;

        this.loginURL = loginURL;

        this.authApiBaseURL = authApiBaseUrl;

        this.allowOriginUrl = allowOriginUrl;

        this.allowMethods = allowMethods;


    }


    /**

     * Creates a CORS configuration bean

     */

    @Bean

    public CorsConfigurationSource corsConfigurationSource() {

        CorsConfiguration configuration = new CorsConfiguration();

        configuration.setAllowedOrigins(List.of("https://ekam.npci.org.in","http://localhost:3003"));

        configuration.setAllowedMethods(List.of("GET", "POST", "DELETE", "PUT"));

        configuration.setAllowedHeaders(List.of("*"));

        configuration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        source.registerCorsConfiguration("/**", configuration);

        return source;

    }

    /**

     * Configures security settings including authentication, authorization, CORS, CSRF, and JWT filtering

     */

//    @Bean

//    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity,

//                                                   JwtAuthenticationFilter jwtAuthenticationFilter,

//                                                   JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint)

//            throws Exception {

//        httpSecurity

//                .headers(headers -&amp;gt; headers

//                        .httpStrictTransportSecurity(hsts -&amp;gt; hsts.includeSubDomains(true).maxAgeInSeconds(31536000))

//                        .contentSecurityPolicy(csp -&amp;gt; csp.policyDirectives("default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'"))

//                        .frameOptions(frameOptions -&amp;gt; frameOptions.deny())); // Prevent Clickjacking

//

//

//        httpSecurity

//                .cors(cors -&amp;gt; cors.configurationSource(corsConfigurationSource()))

//                .csrf(csrf -&amp;gt; csrf.disable())

//                .authorizeHttpRequests(auth -&amp;gt; auth

//                        .requestMatchers(registrationURL, loginURL, "/pcom_bk/api/v1/redis/get/**").permitAll()

//                        .anyRequest().permitAll()) // Restrict other endpoints

//                .exceptionHandling(exception -&amp;gt; exception.authenticationEntryPoint(jwtAuthenticationEntryPoint))

//                .sessionManagement(session -&amp;gt; session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

//

//        httpSecurity.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

//

//        return httpSecurity.build();

//    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity,
                                                   JwtAuthenticationFilter jwtAuthenticationFilter,
                                                   JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint) throws Exception {

        httpSecurity
                .headers(headers -&amp;gt; headers
                        .addHeaderWriter((request, response) -&amp;gt; {
                            response.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload");
                        })
                        .xssProtection(Customizer.withDefaults())
                        .addHeaderWriter((request, response) -&amp;gt; {
                            response.setHeader("Content-Security-Policy",
                                    "default-src 'self'; " +
                                            "script-src 'self'; " +
                                            "frame-ancestors 'self'; " +
                                            "img-src 'self'; " +
                                            "style-src 'self'; " +
                                            "object-src 'none'; " +
                                            "frame-src 'self'; " +
                                            "form-action 'self'; " +
                                            "media-src 'self';"
                            );
                        })
                        .addHeaderWriter((request, response) -&amp;gt; {
                            response.setHeader("Expect-CT", "max-age=3600, enforce");
                        })
                        .addHeaderWriter((request, response) -&amp;gt; {
                            response.setHeader("X-XSS-Protection", "1; mode=block");
                        })
                        .referrerPolicy(referrer -&amp;gt; referrer
                                .policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.SAME_ORIGIN)
                        )
                        .addHeaderWriter((request, response) -&amp;gt; {
                            response.setHeader("X-Content-Type-Options", "nosniff");
                        })
                )
                .cors(Customizer.withDefaults())
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(auth -&amp;gt; auth
                        .requestMatchers(authApiBaseURL + registrationURL + "/**",
                                authApiBaseURL + loginURL + "/**",
                                "/InfraBk/api/v1/inventory/flushDb",
                                "/InfraBk/api/v1/inventory/upload-inventory")
                        .permitAll()
                        .anyRequest()
                        .authenticated()
                )
                .exceptionHandling(exception -&amp;gt; exception
                        .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                )
                .sessionManagement(session -&amp;gt; session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        return httpSecurity.build();
    }



    @Bean

    public InMemoryUserDetailsManager userDetailsManager() {

        return new InMemoryUserDetailsManager();

    }

    /**

     * Bean to encode passwords

     */

    @Bean

    public PasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();

    }

    /**

     * Provides the authentication manager

     */

    @Bean

    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)

            throws Exception {

        return authenticationConfiguration.getAuthenticationManager();

    }

}


fixed these issues 3. Remove duplicate security headers
    X-Content-Type-Options
    X-XSS-Protection: 0,  set this header to 1 and mode = block
    X-Frame-Options
    Strict-Transport-Security

1. set Access Control Allow Credentials header to False

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>webdev</category>
    </item>
  </channel>
</rss>
